diff --git a/openmeter/billing/charges/charge.go b/openmeter/billing/charges/charge.go index 5b24fb0ecb..471e95e1ca 100644 --- a/openmeter/billing/charges/charge.go +++ b/openmeter/billing/charges/charge.go @@ -7,12 +7,14 @@ import ( "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" ) type Charge struct { t meta.ChargeType flatFee *flatfee.Charge + usageBased *usagebased.Charge creditPurchase *creditpurchase.Charge } @@ -20,7 +22,7 @@ func (c Charge) Type() meta.ChargeType { return c.t } -func NewCharge[T flatfee.Charge | creditpurchase.Charge](ch T) Charge { +func NewCharge[T flatfee.Charge | usagebased.Charge | creditpurchase.Charge](ch T) Charge { switch v := any(ch).(type) { case flatfee.Charge: return Charge{ @@ -32,6 +34,11 @@ func NewCharge[T flatfee.Charge | creditpurchase.Charge](ch T) Charge { t: meta.ChargeTypeCreditPurchase, creditPurchase: &v, } + case usagebased.Charge: + return Charge{ + t: meta.ChargeTypeUsageBased, + usageBased: &v, + } } return Charge{} @@ -51,6 +58,12 @@ func (c Charge) Validate() error { } return c.creditPurchase.Validate() + case meta.ChargeTypeUsageBased: + if c.usageBased == nil { + return fmt.Errorf("usage based charge is nil") + } + + return c.usageBased.Validate() } return fmt.Errorf("invalid charge type: %s", c.t) @@ -80,6 +93,14 @@ func (c Charge) AsCreditPurchaseCharge() (creditpurchase.Charge, error) { return *c.creditPurchase, nil } +func (c Charge) AsUsageBasedCharge() (usagebased.Charge, error) { + if c.t != meta.ChargeTypeUsageBased { + return usagebased.Charge{}, fmt.Errorf("charge is not a usage based charge") + } + + return *c.usageBased, nil +} + func (c Charge) GetChargeID() (meta.ChargeID, error) { switch c.t { case meta.ChargeTypeFlatFee: @@ -94,6 +115,12 @@ func (c Charge) GetChargeID() (meta.ChargeID, error) { } return c.creditPurchase.GetChargeID(), nil + case meta.ChargeTypeUsageBased: + if c.usageBased == nil { + return meta.ChargeID{}, fmt.Errorf("usage based charge is nil") + } + + return c.usageBased.GetChargeID(), nil } return meta.ChargeID{}, fmt.Errorf("invalid charge type: %s", c.t) @@ -118,9 +145,10 @@ type ChargeIntent struct { flatFee *flatfee.Intent creditPurchase *creditpurchase.Intent + usageBased *usagebased.Intent } -func NewChargeIntent[T flatfee.Intent | creditpurchase.Intent](ch T) ChargeIntent { +func NewChargeIntent[T flatfee.Intent | usagebased.Intent | creditpurchase.Intent](ch T) ChargeIntent { switch v := any(ch).(type) { case flatfee.Intent: return ChargeIntent{ @@ -132,6 +160,11 @@ func NewChargeIntent[T flatfee.Intent | creditpurchase.Intent](ch T) ChargeInten t: meta.ChargeTypeCreditPurchase, creditPurchase: &v, } + case usagebased.Intent: + return ChargeIntent{ + t: meta.ChargeTypeUsageBased, + usageBased: &v, + } } return ChargeIntent{} @@ -155,6 +188,12 @@ func (i ChargeIntent) Validate() error { } return i.creditPurchase.Validate() + case meta.ChargeTypeUsageBased: + if i.usageBased == nil { + return fmt.Errorf("usage based is nil") + } + + return i.usageBased.Validate() } return fmt.Errorf("invalid charge type: %s", i.t) @@ -184,6 +223,18 @@ func (i ChargeIntent) AsCreditPurchaseIntent() (creditpurchase.Intent, error) { return *i.creditPurchase, nil } +func (i ChargeIntent) AsUsageBasedIntent() (usagebased.Intent, error) { + if i.t != meta.ChargeTypeUsageBased { + return usagebased.Intent{}, fmt.Errorf("charge is not a usage based charge") + } + + if i.usageBased == nil { + return usagebased.Intent{}, fmt.Errorf("usage based is nil") + } + + return *i.usageBased, nil +} + type ChargeIntents []ChargeIntent func (i ChargeIntents) Validate() error { @@ -201,12 +252,14 @@ func (i ChargeIntents) Validate() error { type ChargeIntentsByType struct { FlatFee []WithIndex[flatfee.Intent] CreditPurchase []WithIndex[creditpurchase.Intent] + UsageBased []WithIndex[usagebased.Intent] } func (i ChargeIntents) ByType() (ChargeIntentsByType, error) { out := ChargeIntentsByType{ FlatFee: make([]WithIndex[flatfee.Intent], 0, len(i)), CreditPurchase: make([]WithIndex[creditpurchase.Intent], 0, len(i)), + UsageBased: make([]WithIndex[usagebased.Intent], 0, len(i)), } for idx, ch := range i { @@ -225,6 +278,13 @@ func (i ChargeIntents) ByType() (ChargeIntentsByType, error) { } out.CreditPurchase = append(out.CreditPurchase, WithIndex[creditpurchase.Intent]{Index: idx, Value: creditPurchase}) + case meta.ChargeTypeUsageBased: + usageBased, err := ch.AsUsageBasedIntent() + if err != nil { + return ChargeIntentsByType{}, fmt.Errorf("converting usage based intent[%d]: %w", idx, err) + } + + out.UsageBased = append(out.UsageBased, WithIndex[usagebased.Intent]{Index: idx, Value: usageBased}) default: return ChargeIntentsByType{}, fmt.Errorf("unsupported charge type[%d]: %s", idx, ch.Type()) } diff --git a/openmeter/billing/charges/service/create.go b/openmeter/billing/charges/service/create.go index a00e902f91..f71fa631f0 100644 --- a/openmeter/billing/charges/service/create.go +++ b/openmeter/billing/charges/service/create.go @@ -10,7 +10,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/billing/charges" "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" - "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" "github.com/openmeterio/openmeter/openmeter/customer" "github.com/openmeterio/openmeter/pkg/currencyx" "github.com/openmeterio/openmeter/pkg/framework/transaction" @@ -21,14 +21,6 @@ func (s *service) Create(ctx context.Context, input charges.CreateInput) (charge return nil, err } - // Let's validate for unsupported charge types while we are building out the service - for _, charge := range input.Intents { - switch charge.Type() { - case meta.ChargeTypeUsageBased: - return nil, fmt.Errorf("unsupported charge type %s: %w", charge.Type(), meta.ErrUnsupported) - } - } - return transaction.Run(ctx, s.adapter, func(ctx context.Context) (charges.Charges, error) { intentsByType, err := input.Intents.ByType() if err != nil { @@ -71,6 +63,39 @@ func (s *service) Create(ctx context.Context, input charges.CreateInput) (charge } } + // Let's create all the usage based charges in bulk + usageBasedCharges, err := s.usageBasedService.Create(ctx, usagebased.CreateInput{ + Namespace: input.Namespace, + Intents: lo.Map(intentsByType.UsageBased, func(intent charges.WithIndex[usagebased.Intent], _ int) usagebased.Intent { + return intent.Value + }), + }) + if err != nil { + return nil, err + } + + createdCharges = append( + createdCharges, + lo.Map(usageBasedCharges, func(charge usagebased.ChargeWithGatheringLine, idx int) charges.WithIndex[charges.Charge] { + return charges.WithIndex[charges.Charge]{ + Index: intentsByType.UsageBased[idx].Index, + Value: charges.NewCharge(charge.Charge), + } + })..., + ) + + for _, charge := range usageBasedCharges { + if charge.GatheringLineToCreate != nil { + gatheringLinesToCreate = append(gatheringLinesToCreate, gatheringLineWithCustomerID{ + gatheringLine: *charge.GatheringLineToCreate, + customerID: customer.CustomerID{ + Namespace: input.Namespace, + ID: charge.Charge.Intent.CustomerID, + }, + }) + } + } + // Let's generate the gathering lines for the flat fees if err := s.createGatheringLines(ctx, gatheringLinesToCreate); err != nil { return nil, err diff --git a/openmeter/billing/charges/service/get.go b/openmeter/billing/charges/service/get.go index 6a02759a8a..5405a5a6bf 100644 --- a/openmeter/billing/charges/service/get.go +++ b/openmeter/billing/charges/service/get.go @@ -10,6 +10,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" "github.com/openmeterio/openmeter/pkg/framework/transaction" ) @@ -70,10 +71,6 @@ func (s *service) GetByIDs(ctx context.Context, input charges.GetByIDsInput) (ch if err := refType.Validate(); err != nil { return nil, err } - - if refType == meta.ChargeTypeUsageBased { - return nil, fmt.Errorf("usage based charges are not supported: %w", meta.ErrUnsupported) - } } out := make(charges.Charges, len(chargesWithIndex)) @@ -97,6 +94,24 @@ func (s *service) GetByIDs(ctx context.Context, input charges.GetByIDsInput) (ch nrFetched++ } + // Let's fetch usage based charges + usageBasedCharges, err := s.usageBasedService.GetByIDs(ctx, usagebased.GetByIDsInput{ + Namespace: input.Namespace, + Charges: lo.Map(chargesByType[meta.ChargeTypeUsageBased], func(chargeMeta charges.WithIndex[meta.Charge], _ int) meta.Charge { + return chargeMeta.Value + }), + Expands: input.Expands, + }) + if err != nil { + return nil, err + } + + for i, usageBasedCharge := range usageBasedCharges { + targetIndex := chargesByType[meta.ChargeTypeUsageBased][i].Index + out[targetIndex] = charges.NewCharge(usageBasedCharge) + nrFetched++ + } + // Let's fetch credit purchases creditPurchases, err := s.creditPurchaseService.GetByIDs(ctx, creditpurchase.GetByIDsInput{ Namespace: input.Namespace, diff --git a/openmeter/billing/charges/service/handlers_test.go b/openmeter/billing/charges/service/handlers_test.go index d3aeef2dfc..7190bfbf57 100644 --- a/openmeter/billing/charges/service/handlers_test.go +++ b/openmeter/billing/charges/service/handlers_test.go @@ -120,6 +120,16 @@ func (h *creditPurchaseTestHandler) Reset() { *h = creditPurchaseTestHandler{} } +type usageBasedTestHandler struct{} + +func newUsageBasedTestHandler() *usageBasedTestHandler { + return &usageBasedTestHandler{} +} + +func (h *usageBasedTestHandler) Reset() { + *h = usageBasedTestHandler{} +} + // helpers type countedLedgerTransactionCallback[T any] struct { diff --git a/openmeter/billing/charges/service/service.go b/openmeter/billing/charges/service/service.go index a89342bc33..f385884d08 100644 --- a/openmeter/billing/charges/service/service.go +++ b/openmeter/billing/charges/service/service.go @@ -8,6 +8,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase" "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" ) type service struct { @@ -18,6 +19,7 @@ type service struct { flatFeeService flatfee.Service creditPurchaseService creditpurchase.Service + usageBasedService usagebased.Service } type Config struct { @@ -26,6 +28,7 @@ type Config struct { FlatFeeService flatfee.Service CreditPurchaseService creditpurchase.Service + UsageBasedService usagebased.Service BillingService billing.Service } @@ -49,6 +52,10 @@ func (c Config) Validate() error { errs = append(errs, errors.New("credit purchase service cannot be null")) } + if c.UsageBasedService == nil { + errs = append(errs, errors.New("usage based service cannot be null")) + } + if c.MetaAdapter == nil { errs = append(errs, errors.New("meta adapter cannot be null")) } @@ -67,6 +74,7 @@ func New(config Config) (*service, error) { metaAdapter: config.MetaAdapter, flatFeeService: config.FlatFeeService, creditPurchaseService: config.CreditPurchaseService, + usageBasedService: config.UsageBasedService, } standardInvoiceEventHandler := &standardInvoiceEventHandler{ diff --git a/openmeter/billing/charges/service/service_test.go b/openmeter/billing/charges/service/service_test.go index 94d107c93c..618d8da7c1 100644 --- a/openmeter/billing/charges/service/service_test.go +++ b/openmeter/billing/charges/service/service_test.go @@ -31,6 +31,9 @@ import ( "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" "github.com/openmeterio/openmeter/openmeter/billing/charges/models/ledgertransaction" "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + usagebasedadapter "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased/adapter" + usagebasedservice "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased/service" "github.com/openmeterio/openmeter/openmeter/customer" "github.com/openmeterio/openmeter/openmeter/productcatalog" "github.com/openmeterio/openmeter/pkg/clock" @@ -48,6 +51,7 @@ type ChargesServiceTestSuite struct { Charges *service FlatFeeTestHandler *flatFeeTestHandler CreditPurchaseTestHandler *creditPurchaseTestHandler + UsageBasedTestHandler *usageBasedTestHandler } func TestChargesService(t *testing.T) { @@ -59,6 +63,7 @@ func (s *ChargesServiceTestSuite) SetupSuite() { s.FlatFeeTestHandler = newFlatFeeTestHandler() s.CreditPurchaseTestHandler = newCreditPurchaseTestHandler() + s.UsageBasedTestHandler = newUsageBasedTestHandler() metaAdapter, err := metaadapter.New(metaadapter.Config{ Client: s.DBClient, @@ -94,6 +99,20 @@ func (s *ChargesServiceTestSuite) SetupSuite() { }) s.NoError(err) + usageBasedAdapter, err := usagebasedadapter.New(usagebasedadapter.Config{ + Client: s.DBClient, + Logger: slog.Default(), + MetaAdapter: metaAdapter, + }) + s.NoError(err) + + usageBasedService, err := usagebasedservice.New(usagebasedservice.Config{ + Adapter: usageBasedAdapter, + Handler: s.UsageBasedTestHandler, + MetaAdapter: metaAdapter, + }) + s.NoError(err) + chargesAdapter, err := adapter.New(adapter.Config{ Client: s.DBClient, Logger: slog.Default(), @@ -106,6 +125,7 @@ func (s *ChargesServiceTestSuite) SetupSuite() { MetaAdapter: metaAdapter, FlatFeeService: flatFeeService, CreditPurchaseService: creditPurchaseService, + UsageBasedService: usageBasedService, BillingService: s.BillingService, }) @@ -116,6 +136,7 @@ func (s *ChargesServiceTestSuite) SetupSuite() { func (s *ChargesServiceTestSuite) TeardownTest() { s.FlatFeeTestHandler.Reset() s.CreditPurchaseTestHandler.Reset() + s.UsageBasedTestHandler.Reset() } func (s *ChargesServiceTestSuite) TestFlatFeePartialCreditRealizations() { @@ -417,9 +438,14 @@ func (s *ChargesServiceTestSuite) createMockChargeIntent(input createMockChargeI return charges.NewChargeIntent(flatFeeIntent) } - s.FailNow("not implemented: usage based intents") - - return charges.ChargeIntent{} + usageBasedIntent := usagebased.Intent{ + Intent: intentMeta, + FeatureKey: input.featureKey, + Price: lo.FromPtr(input.price), + InvoiceAt: invoiceAt, + SettlementMode: lo.CoalesceOrEmpty(input.settlementMode, productcatalog.InvoiceOnlySettlementMode), + } + return charges.NewChargeIntent(usageBasedIntent) } func (s *ChargesServiceTestSuite) mustGetChargeByID(chargeID meta.ChargeID) charges.Charge { @@ -751,3 +777,88 @@ func (s *ChargesServiceTestSuite) TestExternalAuthorizedCreditPurchaseManuallySe s.Equal(meta.ChargeStatusFinal, res.Status) }) } + +func (s *ChargesServiceTestSuite) TestUsageBasedPartialCreditRealizations() { + ctx := context.Background() + ns := s.GetUniqueNamespace("charges-service-usage-based-partial-credit-realizations") + + customInvoicing := s.SetupCustomInvoicing(ns) + + cust := s.CreateTestCustomer(ns, "test-subject") + s.NotEmpty(cust.ID) + + _ = s.ProvisionBillingProfile(ctx, ns, customInvoicing.App.GetID(), + billingtest.WithProgressiveBilling(), + billingtest.WithCollectionInterval(datetime.MustParseDuration(s.T(), "PT1H")), + billingtest.WithManualApproval(), + ) + + const ( + usageBasedName = "usage-based" + ) + + servicePeriod := timeutil.ClosedPeriod{ + From: datetime.MustParseTimeInLocation(s.T(), "2026-01-01T00:00:00Z", time.UTC).AsTime(), + To: datetime.MustParseTimeInLocation(s.T(), "2026-02-01T00:00:00Z", time.UTC).AsTime(), + } + + apiRequestsTotal := s.SetupApiRequestsTotalFeature(ctx, ns) + + clock.SetTime(servicePeriod.From) + + usageBasedChargeID := meta.ChargeID{} + + s.Run("create new upcoming charges", func() { + res, err := s.Charges.Create(ctx, charges.CreateInput{ + Namespace: ns, + Intents: []charges.ChargeIntent{ + s.createMockChargeIntent(createMockChargeIntentInput{ + customer: cust.GetID(), + currency: USD, + servicePeriod: servicePeriod, + settlementMode: productcatalog.CreditThenInvoiceSettlementMode, + price: productcatalog.NewPriceFrom(productcatalog.UnitPrice{ + Amount: alpacadecimal.NewFromFloat(100), + }), + name: usageBasedName, + managedBy: billing.SubscriptionManagedLine, + uniqueReferenceID: usageBasedName, + featureKey: apiRequestsTotal.Feature.Key, + }), + }, + }) + s.NoError(err) + + s.Len(res, 1) + s.Equal(res[0].Type(), meta.ChargeTypeUsageBased) + usageBasedCharge, err := res[0].AsUsageBasedCharge() + s.NoError(err) + + gatheringInvoices, err := s.BillingService.ListGatheringInvoices(ctx, billing.ListGatheringInvoicesInput{ + Namespaces: []string{ns}, + Customers: []string{cust.ID}, + Currencies: []currencyx.Code{currencyx.Code(currency.USD)}, + Expand: []billing.GatheringInvoiceExpand{billing.GatheringInvoiceExpandLines}, + }) + s.NoError(err) + s.Len(gatheringInvoices.Items, 1) + gatheringInvoice := gatheringInvoices.Items[0] + + lines := gatheringInvoice.Lines.OrEmpty() + s.Len(lines, 1) + gatheringLine := lines[0] + + s.Equal(usageBasedCharge.ID, *gatheringLine.ChargeID) + + // TODO: validate periods, price, etc. + + fetchedCharge := s.mustGetChargeByID(usageBasedCharge.GetChargeID()) + fetchedUsageBasedCharge, err := fetchedCharge.AsUsageBasedCharge() + s.NoError(err) + s.Equal(usageBasedCharge, fetchedUsageBasedCharge) + + usageBasedChargeID = usageBasedCharge.GetChargeID() + }) + + s.NotEmpty(usageBasedChargeID) +} diff --git a/openmeter/billing/charges/usagebased/adapter.go b/openmeter/billing/charges/usagebased/adapter.go new file mode 100644 index 0000000000..d613962c93 --- /dev/null +++ b/openmeter/billing/charges/usagebased/adapter.go @@ -0,0 +1,15 @@ +package usagebased + +import ( + "context" + + "github.com/openmeterio/openmeter/pkg/framework/entutils" +) + +type Adapter interface { + CreateCharges(ctx context.Context, charges CreateInput) ([]Charge, error) + UpdateCharge(ctx context.Context, charge Charge) error + GetByIDs(ctx context.Context, ids GetByIDsInput) ([]Charge, error) + + entutils.TxCreator +} diff --git a/openmeter/billing/charges/usagebased/adapter/adapter.go b/openmeter/billing/charges/usagebased/adapter/adapter.go new file mode 100644 index 0000000000..fc1ea1d6fe --- /dev/null +++ b/openmeter/billing/charges/usagebased/adapter/adapter.go @@ -0,0 +1,81 @@ +package adapter + +import ( + "context" + "database/sql" + "errors" + "fmt" + "log/slog" + + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + entdb "github.com/openmeterio/openmeter/openmeter/ent/db" + "github.com/openmeterio/openmeter/pkg/framework/entutils" + "github.com/openmeterio/openmeter/pkg/framework/transaction" +) + +type Config struct { + MetaAdapter meta.Adapter + Client *entdb.Client + Logger *slog.Logger +} + +func (c Config) Validate() error { + if c.Client == nil { + return errors.New("ent client is required") + } + + if c.Logger == nil { + return errors.New("logger is required") + } + + if c.MetaAdapter == nil { + return errors.New("meta adapter is required") + } + + return nil +} + +func New(config Config) (usagebased.Adapter, error) { + if err := config.Validate(); err != nil { + return nil, err + } + + return &adapter{ + db: config.Client, + logger: config.Logger, + metaAdapter: config.MetaAdapter, + }, nil +} + +var _ usagebased.Adapter = (*adapter)(nil) + +type adapter struct { + db *entdb.Client + logger *slog.Logger + metaAdapter meta.Adapter +} + +func (a *adapter) Tx(ctx context.Context) (context.Context, transaction.Driver, error) { + txCtx, rawConfig, eDriver, err := a.db.HijackTx(ctx, &sql.TxOptions{ + ReadOnly: false, + }) + if err != nil { + return nil, nil, fmt.Errorf("failed to hijack transaction: %w", err) + } + return txCtx, entutils.NewTxDriver(eDriver, rawConfig), nil +} + +func (a *adapter) WithTx(ctx context.Context, tx *entutils.TxDriver) *adapter { + txDb := entdb.NewTxClientFromRawConfig(ctx, *tx.GetConfig()) + + return &adapter{ + db: txDb.Client(), + logger: a.logger, + metaAdapter: a.metaAdapter, + } +} + +func (a *adapter) Self() *adapter { + return a +} diff --git a/openmeter/billing/charges/usagebased/adapter/charge.go b/openmeter/billing/charges/usagebased/adapter/charge.go new file mode 100644 index 0000000000..b0d4f9f153 --- /dev/null +++ b/openmeter/billing/charges/usagebased/adapter/charge.go @@ -0,0 +1,164 @@ +package adapter + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db" + dbchargeusagebased "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/pkg/framework/entutils" + "github.com/openmeterio/openmeter/pkg/slicesx" + "github.com/samber/lo" +) + +func (a *adapter) UpdateCharge(ctx context.Context, charge usagebased.Charge) error { + if err := charge.Validate(); err != nil { + return err + } + + return entutils.TransactingRepoWithNoValue(ctx, a, func(ctx context.Context, tx *adapter) error { + _, err := tx.metaAdapter.UpdateStatus(ctx, meta.UpdateStatusInput{ + ChargeID: charge.GetChargeID(), + Status: charge.Status, + }) + if err != nil { + return err + } + + _, err = tx.db.ChargeUsageBased.UpdateOneID(charge.ID). + Where(dbchargeusagebased.NamespaceEQ(charge.Namespace)). + SetDiscounts(&charge.Intent.Discounts). + Save(ctx) + if err != nil { + return err + } + + return nil + }) +} + +func (a *adapter) CreateCharges(ctx context.Context, in usagebased.CreateInput) ([]usagebased.Charge, error) { + if err := in.Validate(); err != nil { + return nil, err + } + + return entutils.TransactingRepo(ctx, a, func(ctx context.Context, tx *adapter) ([]usagebased.Charge, error) { + chargeMetas, err := tx.metaAdapter.Create(ctx, meta.CreateInput{ + Namespace: in.Namespace, + Intents: slicesx.Map(in.Intents, func(intent usagebased.Intent) meta.IntentCreate { + return meta.IntentCreate{ + Intent: intent.Intent, + Type: meta.ChargeTypeUsageBased, + } + }), + }) + if err != nil { + return nil, err + } + + if len(chargeMetas) != len(in.Intents) { + return nil, fmt.Errorf("expected %d charge metas, got %d", len(in.Intents), len(chargeMetas)) + } + + creates := make([]*db.ChargeUsageBasedCreate, 0, len(chargeMetas)) + for idx, chargeMeta := range chargeMetas { + create, err := tx.buildCreateUsageBasedCharge(ctx, chargeMeta, in.Intents[idx]) + if err != nil { + return nil, err + } + creates = append(creates, create) + } + entities, err := tx.db.ChargeUsageBased.CreateBulk(creates...).Save(ctx) + if err != nil { + return nil, err + } + + out := make([]usagebased.Charge, 0, len(entities)) + for idx, entity := range entities { + charge, err := MapUsageBasedChargeFromDB(entity, chargeMetas[idx], meta.ExpandNone) + if err != nil { + return nil, err + } + out = append(out, charge) + } + return out, nil + }) +} + +func (a *adapter) GetByIDs(ctx context.Context, input usagebased.GetByIDsInput) ([]usagebased.Charge, error) { + if err := input.Validate(); err != nil { + return nil, err + } + + return entutils.TransactingRepo(ctx, a, func(ctx context.Context, tx *adapter) ([]usagebased.Charge, error) { + query := tx.db.ChargeUsageBased.Query(). + Where(dbchargeusagebased.Namespace(input.Namespace)). + Where(dbchargeusagebased.IDIn( + lo.Map(input.Charges, func(charge meta.Charge, idx int) string { + return charge.ID + })..., + )) + + if input.Expands.Has(meta.ExpandRealizations) { + query = query.WithRuns( + func(runs *db.ChargeUsageBasedRunsQuery) { + runs.WithCreditAllocations(). + WithInvoicedUsage(). + WithPayment() + }, + ) + } + + entities, err := query.All(ctx) + if err != nil { + return nil, err + } + + entitiesMapped := make([]usagebased.Charge, 0, len(entities)) + for idx, entity := range entities { + charge, err := MapUsageBasedChargeFromDB(entity, input.Charges[idx], input.Expands) + if err != nil { + return nil, err + } + entitiesMapped = append(entitiesMapped, charge) + } + + entitiesByID := lo.GroupBy(entitiesMapped, func(charge usagebased.Charge) string { + return charge.ID + }) + + var errs []error + out := make([]usagebased.Charge, 0, len(input.Charges)) + for _, charge := range input.Charges { + charges, ok := entitiesByID[charge.ID] + if !ok { + errs = append(errs, fmt.Errorf("charge not found: %s", charge.ID)) + continue + } + + out = append(out, charges[0]) + } + + if len(errs) > 0 { + return nil, errors.Join(errs...) + } + + return out, nil + }) +} + +func (a *adapter) buildCreateUsageBasedCharge(ctx context.Context, chargeMeta meta.Charge, intent usagebased.Intent) (*db.ChargeUsageBasedCreate, error) { + return a.db.ChargeUsageBased.Create(). + SetNamespace(chargeMeta.Namespace). + SetID(chargeMeta.ID). + SetChargeID(chargeMeta.ID). + SetDiscounts(&intent.Discounts). + SetPrice(&intent.Price). + SetFeatureKey(intent.FeatureKey). + SetInvoiceAt(intent.InvoiceAt.In(time.UTC)). + SetSettlementMode(intent.SettlementMode), nil +} diff --git a/openmeter/billing/charges/usagebased/adapter/mapper.go b/openmeter/billing/charges/usagebased/adapter/mapper.go new file mode 100644 index 0000000000..ed8e8c93e1 --- /dev/null +++ b/openmeter/billing/charges/usagebased/adapter/mapper.go @@ -0,0 +1,95 @@ +package adapter + +import ( + "fmt" + + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/invoicedusage" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + entdb "github.com/openmeterio/openmeter/openmeter/ent/db" + "github.com/openmeterio/openmeter/pkg/framework/entutils" + "github.com/openmeterio/openmeter/pkg/models" + "github.com/openmeterio/openmeter/pkg/slicesx" + "github.com/samber/lo" +) + +// MapUsageBasedChargeFromDB converts a DB Charge entity (with loaded UsageBased edge) to a UsageBasedCharge. +func MapUsageBasedChargeFromDB(entity *entdb.ChargeUsageBased, chargeMeta meta.Charge, expands meta.Expands) (usagebased.Charge, error) { + charge := usagebased.Charge{ + ManagedResource: chargeMeta.ManagedResource, + Status: chargeMeta.Status, + Intent: usagebased.Intent{ + Intent: chargeMeta.Intent, + InvoiceAt: entity.InvoiceAt.UTC(), + SettlementMode: entity.SettlementMode, + FeatureKey: entity.FeatureKey, + Discounts: lo.FromPtr(entity.Discounts), + Price: lo.FromPtr(entity.Price), + }, + } + + if expands.Has(meta.ExpandRealizations) { + dbRuns, err := entity.Edges.RunsOrErr() + if err != nil { + return usagebased.Charge{}, fmt.Errorf("mapping usage based charge [id=%s]: %w", entity.ID, err) + } + + runs, err := slicesx.MapWithErr(dbRuns, func(run *entdb.ChargeUsageBasedRuns) (usagebased.RealizationRun, error) { + return MapRealizationRunFromDB(run) + }) + if err != nil { + return usagebased.Charge{}, fmt.Errorf("mapping usage based charge [id=%s]: %w", entity.ID, err) + } + + if len(runs) > 0 { + // Force nil value for easier testing + charge.State.RealizationRuns = runs + } + } + + return charge, nil +} + +func MapRealizationRunFromDB(dbRun *entdb.ChargeUsageBasedRuns) (usagebased.RealizationRun, error) { + run := usagebased.RealizationRun{ + NamespacedID: models.NamespacedID{ + Namespace: dbRun.Namespace, + ID: dbRun.ID, + }, + ManagedModel: entutils.MapTimeMixinFromDB(dbRun), + Type: dbRun.Type, + AsOf: dbRun.Asof, + MeterValue: dbRun.MeterValue, + } + + dbCreditsAllocated, err := dbRun.Edges.CreditAllocationsOrErr() + if _, ok := lo.ErrorsAs[*entdb.NotLoadedError](err); ok { + return usagebased.RealizationRun{}, fmt.Errorf("credits allocated not loaded for usage based charge run [id=%s]", dbRun.ID) + } + + run.CreditsAllocated = lo.Map(dbCreditsAllocated, func(credit *entdb.ChargeUsageBasedRunCreditAllocations, _ int) creditrealization.Realization { + return creditrealization.MapFromDB(credit) + }) + + dbInvoiceUsage, err := dbRun.Edges.InvoicedUsageOrErr() + if _, ok := lo.ErrorsAs[*entdb.NotLoadedError](err); ok { + return usagebased.RealizationRun{}, fmt.Errorf("invoice usage not loaded for usage based charge run [id=%s]", dbRun.ID) + } + + if dbInvoiceUsage != nil { + run.InvoiceUsage = lo.ToPtr(invoicedusage.MapAccruedUsageFromDB(dbInvoiceUsage)) + } + + dbPayment, err := dbRun.Edges.PaymentOrErr() + if _, ok := lo.ErrorsAs[*entdb.NotLoadedError](err); ok { + return usagebased.RealizationRun{}, fmt.Errorf("payment not loaded for usage based charge run [id=%s]", dbRun.ID) + } + + if dbPayment != nil { + run.Payment = lo.ToPtr(payment.MapInvoicedFromDB(dbPayment)) + } + + return run, nil +} diff --git a/openmeter/billing/charges/usagebased/charge.go b/openmeter/billing/charges/usagebased/charge.go new file mode 100644 index 0000000000..6c870198ac --- /dev/null +++ b/openmeter/billing/charges/usagebased/charge.go @@ -0,0 +1,198 @@ +package usagebased + +import ( + "errors" + "fmt" + "slices" + "time" + + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/invoicedusage" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/models" +) + +var _ meta.ChargeAccessor = (*Charge)(nil) + +type Charge struct { + meta.ManagedResource + + Intent Intent `json:"intent"` + Status meta.ChargeStatus `json:"status"` + + State State `json:"state"` +} + +func (c Charge) Validate() error { + var errs []error + + if err := c.ManagedResource.Validate(); err != nil { + errs = append(errs, fmt.Errorf("managed resource: %w", err)) + } + + if err := c.Intent.Validate(); err != nil { + errs = append(errs, fmt.Errorf("intent: %w", err)) + } + + if err := c.Status.Validate(); err != nil { + errs = append(errs, fmt.Errorf("status: %w", err)) + } + + if err := c.State.Validate(); err != nil { + errs = append(errs, fmt.Errorf("state: %w", err)) + } + + return errors.Join(errs...) +} + +func (c Charge) GetChargeID() meta.ChargeID { + return meta.ChargeID{ + Namespace: c.Namespace, + ID: c.ID, + } +} + +func (c Charge) ErrorAttributes() models.Attributes { + return models.Attributes{ + "charge_id": c.ID, + "namespace": c.Namespace, + "charge_type": string(meta.ChargeTypeUsageBased), + } +} + +type Intent struct { + meta.Intent + + InvoiceAt time.Time `json:"invoiceAt"` + SettlementMode productcatalog.SettlementMode `json:"settlementMode"` + + FeatureKey string `json:"featureKey"` + + Price productcatalog.Price `json:"price"` + + Discounts productcatalog.Discounts `json:"discounts"` +} + +func (i Intent) Validate() error { + var errs []error + + if err := i.Intent.Validate(); err != nil { + errs = append(errs, fmt.Errorf("intent: %w", err)) + } + + if err := i.SettlementMode.Validate(); err != nil { + errs = append(errs, fmt.Errorf("settlement mode: %w", err)) + } + + if err := i.Discounts.Validate(); err != nil { + errs = append(errs, fmt.Errorf("discounts: %w", err)) + } + + if i.InvoiceAt.IsZero() { + errs = append(errs, fmt.Errorf("invoice at is required")) + } + + if err := i.Price.Validate(); err != nil { + errs = append(errs, fmt.Errorf("price: %w", err)) + } + + return errors.Join(errs...) +} + +type State struct { + RealizationRuns RealizationRuns `json:"realizationRuns"` +} + +func (s State) Validate() error { + return s.RealizationRuns.Validate() +} + +type RealizationRuns []RealizationRun + +func (r RealizationRuns) Validate() error { + var errs []error + for idx, realizationRun := range r { + if err := realizationRun.Validate(); err != nil { + errs = append(errs, fmt.Errorf("realization run[%d]: %w", idx, err)) + } + } + return errors.Join(errs...) +} + +type RealizationRunType string + +const ( + RealizationRunTypeInvoice RealizationRunType = "invoice" +) + +func (t RealizationRunType) Values() []string { + return []string{ + string(RealizationRunTypeInvoice), + } +} + +func (t RealizationRunType) Validate() error { + if !slices.Contains(t.Values(), string(t)) { + return fmt.Errorf("invalid realization run type: %s", t) + } + return nil +} + +type RealizationRun struct { + models.NamespacedID + models.ManagedModel + + Type RealizationRunType `json:"status"` + AsOf time.Time `json:"asOf"` + MeterValue alpacadecimal.Decimal `json:"meterValue"` + + // Realizations + CreditsAllocated creditrealization.Realizations `json:"creditsAllocated"` + InvoiceUsage *invoicedusage.AccruedUsage `json:"invoicedUsage"` + Payment *payment.Invoiced `json:"payment"` +} + +func (r RealizationRun) Validate() error { + var errs []error + + if err := r.NamespacedID.Validate(); err != nil { + errs = append(errs, fmt.Errorf("namespaced id: %w", err)) + } + + if err := r.ManagedModel.Validate(); err != nil { + errs = append(errs, fmt.Errorf("managed model: %w", err)) + } + + if err := r.Type.Validate(); err != nil { + errs = append(errs, fmt.Errorf("type: %w", err)) + } + + if r.MeterValue.IsNegative() { + errs = append(errs, fmt.Errorf("meter value must be positive")) + } + + if r.AsOf.IsZero() { + errs = append(errs, fmt.Errorf("as of must be set")) + } + + if err := r.CreditsAllocated.Validate(); err != nil { + errs = append(errs, fmt.Errorf("credits allocated: %w", err)) + } + + if r.InvoiceUsage != nil { + if err := r.InvoiceUsage.Validate(); err != nil { + errs = append(errs, fmt.Errorf("invoice usage: %w", err)) + } + } + + if r.Payment != nil { + if err := r.Payment.Validate(); err != nil { + errs = append(errs, fmt.Errorf("payment: %w", err)) + } + } + + return errors.Join(errs...) +} diff --git a/openmeter/billing/charges/usagebased/handler.go b/openmeter/billing/charges/usagebased/handler.go new file mode 100644 index 0000000000..0281d29bff --- /dev/null +++ b/openmeter/billing/charges/usagebased/handler.go @@ -0,0 +1,3 @@ +package usagebased + +type Handler interface{} diff --git a/openmeter/billing/charges/usagebased/service.go b/openmeter/billing/charges/usagebased/service.go new file mode 100644 index 0000000000..4db3c57a99 --- /dev/null +++ b/openmeter/billing/charges/usagebased/service.go @@ -0,0 +1,77 @@ +package usagebased + +import ( + "context" + "errors" + "fmt" + + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" +) + +type Service interface { + UsageBasedService + // InvoiceLifecycleHooks +} + +type UsageBasedService interface { + Create(ctx context.Context, input CreateInput) ([]ChargeWithGatheringLine, error) + GetByIDs(ctx context.Context, input GetByIDsInput) ([]Charge, error) +} + +type InvoiceLifecycleHooks interface { + PostLineAssignedToInvoice(ctx context.Context, charge Charge, line billing.GatheringLine) (creditrealization.Realizations, error) + PostInvoiceIssued(ctx context.Context, charge Charge, lineWithHeader billing.StandardLineWithInvoiceHeader) error + PostPaymentAuthorized(ctx context.Context, charge Charge, lineWithHeader billing.StandardLineWithInvoiceHeader) error + PostPaymentSettled(ctx context.Context, charge Charge, lineWithHeader billing.StandardLineWithInvoiceHeader) error +} + +type CreateInput struct { + Namespace string + Intents []Intent +} + +func (i CreateInput) Validate() error { + var errs []error + if i.Namespace == "" { + errs = append(errs, errors.New("namespace is required")) + } + + for idx, intent := range i.Intents { + if err := intent.Validate(); err != nil { + errs = append(errs, fmt.Errorf("intent [%d]: %w", idx, err)) + } + } + + return errors.Join(errs...) +} + +type ChargeWithGatheringLine struct { + Charge Charge + GatheringLineToCreate *billing.GatheringLine +} + +type GetByIDsInput struct { + Namespace string + Expands meta.Expands + Charges meta.Charges +} + +func (i GetByIDsInput) Validate() error { + var errs []error + + if i.Namespace == "" { + errs = append(errs, errors.New("namespace is required")) + } + + if err := i.Charges.Validate(); err != nil { + errs = append(errs, fmt.Errorf("charges: %w", err)) + } + + if err := i.Expands.Validate(); err != nil { + errs = append(errs, fmt.Errorf("expands: %w", err)) + } + + return errors.Join(errs...) +} diff --git a/openmeter/billing/charges/usagebased/service/create.go b/openmeter/billing/charges/usagebased/service/create.go new file mode 100644 index 0000000000..2ef08ecde0 --- /dev/null +++ b/openmeter/billing/charges/usagebased/service/create.go @@ -0,0 +1,111 @@ +package service + +import ( + "context" + "fmt" + + "github.com/samber/lo" + + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/framework/transaction" + "github.com/openmeterio/openmeter/pkg/models" + "github.com/openmeterio/openmeter/pkg/slicesx" + "github.com/openmeterio/openmeter/pkg/timeutil" +) + +func (s *service) Create(ctx context.Context, input usagebased.CreateInput) ([]usagebased.ChargeWithGatheringLine, error) { + if err := input.Validate(); err != nil { + return nil, err + } + + if len(input.Intents) == 0 { + return nil, nil + } + + return transaction.Run(ctx, s.adapter, func(ctx context.Context) ([]usagebased.ChargeWithGatheringLine, error) { + // Let's create all the flat fee charges in bulk + charges, err := s.adapter.CreateCharges(ctx, input) + if err != nil { + return nil, err + } + + return slicesx.MapWithErr(charges, func(charge usagebased.Charge) (usagebased.ChargeWithGatheringLine, error) { + // For credit only flat fees we are not relying on the invoicing stack at all, so we can return early. + if charge.Intent.SettlementMode == productcatalog.CreditOnlySettlementMode { + return usagebased.ChargeWithGatheringLine{ + Charge: charge, + }, nil + } + + return gatheringLineFromUsageBasedCharge(charge) + }) + }) +} + +func gatheringLineFromUsageBasedCharge(flatFee usagebased.Charge) (usagebased.ChargeWithGatheringLine, error) { + intent := flatFee.Intent + + var subscription *billing.SubscriptionReference + if intent.Subscription != nil { + subscription = &billing.SubscriptionReference{ + SubscriptionID: intent.Subscription.SubscriptionID, + PhaseID: intent.Subscription.PhaseID, + ItemID: intent.Subscription.ItemID, + BillingPeriod: timeutil.ClosedPeriod{ + From: intent.BillingPeriod.From, + To: intent.BillingPeriod.To, + }, + } + } + + clonedAnnotations, err := intent.Annotations.Clone() + if err != nil { + return usagebased.ChargeWithGatheringLine{}, fmt.Errorf("cloning annotations: %w", err) + } + + gatheringLine := billing.GatheringLine{ + GatheringLineBase: billing.GatheringLineBase{ + ManagedResource: models.NewManagedResource(models.ManagedResourceInput{ + Namespace: flatFee.Namespace, + Name: intent.Name, + Description: intent.Description, + }), + + Metadata: intent.Metadata.Clone(), + Annotations: clonedAnnotations, + ManagedBy: intent.ManagedBy, + + Price: intent.Price, + FeatureKey: intent.FeatureKey, + + Currency: intent.Currency, + ServicePeriod: intent.ServicePeriod, + InvoiceAt: intent.InvoiceAt, + + TaxConfig: intent.TaxConfig, + + ChargeID: lo.ToPtr(flatFee.ID), + ChildUniqueReferenceID: intent.UniqueReferenceID, + Subscription: subscription, + }, + } + + if intent.Discounts.Usage != nil { + gatheringLine.RateCardDiscounts.Usage = &billing.UsageDiscount{ + UsageDiscount: *intent.Discounts.Usage, + } + } + + if intent.Discounts.Percentage != nil { + gatheringLine.RateCardDiscounts.Percentage = &billing.PercentageDiscount{ + PercentageDiscount: *intent.Discounts.Percentage, + } + } + + return usagebased.ChargeWithGatheringLine{ + Charge: flatFee, + GatheringLineToCreate: &gatheringLine, + }, nil +} diff --git a/openmeter/billing/charges/usagebased/service/get.go b/openmeter/billing/charges/usagebased/service/get.go new file mode 100644 index 0000000000..d44afda346 --- /dev/null +++ b/openmeter/billing/charges/usagebased/service/get.go @@ -0,0 +1,18 @@ +package service + +import ( + "context" + + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/pkg/framework/transaction" +) + +func (s *service) GetByIDs(ctx context.Context, input usagebased.GetByIDsInput) ([]usagebased.Charge, error) { + if err := input.Validate(); err != nil { + return nil, err + } + + return transaction.Run(ctx, s.adapter, func(ctx context.Context) ([]usagebased.Charge, error) { + return s.adapter.GetByIDs(ctx, input) + }) +} diff --git a/openmeter/billing/charges/usagebased/service/service.go b/openmeter/billing/charges/usagebased/service/service.go new file mode 100644 index 0000000000..ffb8d5a2e2 --- /dev/null +++ b/openmeter/billing/charges/usagebased/service/service.go @@ -0,0 +1,50 @@ +package service + +import ( + "errors" + + "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" +) + +type Config struct { + Adapter usagebased.Adapter + Handler usagebased.Handler + MetaAdapter meta.Adapter +} + +func (c Config) Validate() error { + var errs []error + + if c.Adapter == nil { + errs = append(errs, errors.New("adapter cannot be null")) + } + + if c.Handler == nil { + errs = append(errs, errors.New("handler cannot be null")) + } + + if c.MetaAdapter == nil { + errs = append(errs, errors.New("meta adapter cannot be null")) + } + + return errors.Join(errs...) +} + +func New(config Config) (usagebased.Service, error) { + if err := config.Validate(); err != nil { + return nil, err + } + + return &service{ + adapter: config.Adapter, + handler: config.Handler, + metaAdapter: config.MetaAdapter, + }, nil +} + +type service struct { + adapter usagebased.Adapter + handler usagebased.Handler + metaAdapter meta.Adapter +} diff --git a/openmeter/billing/gatheringinvoice.go b/openmeter/billing/gatheringinvoice.go index 00fdb9ab7d..9dbfd531c9 100644 --- a/openmeter/billing/gatheringinvoice.go +++ b/openmeter/billing/gatheringinvoice.go @@ -375,6 +375,8 @@ type GatheringLineBase struct { SplitLineGroupID *string `json:"splitLineGroupID,omitempty"` ChargeID *string `json:"chargeId,omitempty"` + LifecycleHandler LifecycleHandler `json:"lifecycleHandler"` + // TODO: Remove once we have dedicated db field for gathering invoice lines UBPConfigID string `json:"ubpConfigID"` } @@ -705,7 +707,8 @@ func (g GatheringLine) AsNewStandardLine(invoiceID string) (*StandardLine, error Start: g.ServicePeriod.From, End: g.ServicePeriod.To, }, - InvoiceAt: g.InvoiceAt, + InvoiceAt: g.InvoiceAt, + LifecycleHandler: g.LifecycleHandler, TaxConfig: taxConfig, RateCardDiscounts: g.RateCardDiscounts.Clone(), diff --git a/openmeter/billing/lifecycle.go b/openmeter/billing/lifecycle.go new file mode 100644 index 0000000000..290fd6ab62 --- /dev/null +++ b/openmeter/billing/lifecycle.go @@ -0,0 +1,56 @@ +package billing + +import ( + "context" + "fmt" + "slices" +) + +type LifecycleHandler string + +const ( + DefaultLifecycleHandler LifecycleHandler = "default" + ChargesLifecycleHandler LifecycleHandler = "charges" +) + +func (h LifecycleHandler) Values() []string { + return []string{ + string(DefaultLifecycleHandler), + string(ChargesLifecycleHandler), + } +} + +func (h LifecycleHandler) Validate() error { + if !slices.Contains(h.Values(), string(h)) { + return fmt.Errorf("invalid lifecycle handler: %s", h) + } + + return nil +} + +type IsLineBillableResult struct { + IsBillable bool + ValidationError error +} + +type AreLinesBillableResult []IsLineBillableResult + +type InvoiceLifecycleHandler interface { + // AreLinesBillable is used to determine if the lines are billable as of the given time. + AreLinesBillable(ctx context.Context, invoice GatheringInvoice, lines GatheringLines) (AreLinesBillableResult, error) + + // HandleInvoiceCreation is used to handle the creation of the invoice line when creating the standard invoice. + HandleInvoiceCreation(ctx context.Context, line GatheringLines) (StandardLines, error) + + // HandleCollectionSnapshot is invoked when the draft.collecting state is entered. + HandleCollectionSnapshot(ctx context.Context, lines StandardLines) (StandardLines, error) + + // HandleInvoiceIssued is invoked when the invoice is issued. + HandleInvoiceIssued(ctx context.Context, lines StandardLines) error + + // HandlePaymentAuthorized is invoked when the payment is authorized. + HandlePaymentAuthorized(ctx context.Context, lines StandardLines) error + + // HandlePaymentSettled is invoked when the payment is settled. + HandlePaymentSettled(ctx context.Context, lines StandardLines) error +} diff --git a/openmeter/billing/service/lifecycle.go b/openmeter/billing/service/lifecycle.go new file mode 100644 index 0000000000..a5304c85da --- /dev/null +++ b/openmeter/billing/service/lifecycle.go @@ -0,0 +1,60 @@ +package billingservice + +import ( + "context" + "sync" + + "github.com/openmeterio/openmeter/openmeter/billing" + "github.com/samber/lo" +) + +var _ billing.InvoiceLifecycleHandler = (*DefaultInvoiceLifecycleHandler)(nil) + +type DefaultInvoiceLifecycleHandler struct{} + +func (h *DefaultInvoiceLifecycleHandler) AreLinesBillable(ctx context.Context, invoice billing.GatheringInvoice, lines billing.GatheringLines) (billing.AreLinesBillableResult, error) { + return lo.Map(lines, func(line billing.GatheringLine, _ int) billing.IsLineBillableResult { + return billing.IsLineBillableResult{ + IsBillable: true, + ValidationError: nil, + } + }), nil +} + +type LineLifecycleRegistry struct { + mux sync.RWMutex + handlersByName map[billing.LifecycleHandler]billing.InvoiceLifecycleHandler +} + +func NewLineLifecycleRegistry() *LineLifecycleRegistry { + return &LineLifecycleRegistry{ + handlersByName: map[billing.LifecycleHandler]billing.InvoiceLifecycleHandler{ + billing.DefaultLifecycleHandler: &DefaultInvoiceLifecycleHandler{}, + }, + } +} + +func (r *LineLifecycleRegistry) Register(typeName billing.LifecycleHandler, handler billing.InvoiceLifecycleHandler) { + r.mux.Lock() + defer r.mux.Unlock() + + r.handlersByName[typeName] = handler +} + +func (r *LineLifecycleRegistry) Get(ctx context.Context, line billing.LineWithInvoiceHeader) (billing.InvoiceLineLifecycleHandler, error) { + r.mux.RLock() + defer r.mux.RUnlock() + + for _, handler := range r.handlers { + shouldHandle, err := handler.ShouldHandleLine(ctx, line) + if err != nil { + return nil, err + } + + if shouldHandle { + return handler, nil + } + } + + return r.defaultHandler, nil +} diff --git a/openmeter/billing/stdinvoiceline.go b/openmeter/billing/stdinvoiceline.go index 3a92cde7f1..3b78f450c5 100644 --- a/openmeter/billing/stdinvoiceline.go +++ b/openmeter/billing/stdinvoiceline.go @@ -36,9 +36,10 @@ type StandardLineBase struct { InvoiceAt time.Time `json:"invoiceAt"` // Relationships - ParentLineID *string `json:"parentLine,omitempty"` - SplitLineGroupID *string `json:"splitLineGroupId,omitempty"` - ChargeID *string `json:"chargeId,omitempty"` + ParentLineID *string `json:"parentLine,omitempty"` + SplitLineGroupID *string `json:"splitLineGroupId,omitempty"` + ChargeID *string `json:"chargeId,omitempty"` + LifecycleHandler LifecycleHandler `json:"lifecycleHandler"` ChildUniqueReferenceID *string `json:"childUniqueReferenceID,omitempty"` diff --git a/openmeter/ent/db/billinginvoiceline.go b/openmeter/ent/db/billinginvoiceline.go index 8d85edb87e..d7d829a6fa 100644 --- a/openmeter/ent/db/billinginvoiceline.go +++ b/openmeter/ent/db/billinginvoiceline.go @@ -106,6 +106,8 @@ type BillingInvoiceLine struct { SplitLineGroupID *string `json:"split_line_group_id,omitempty"` // ChargeID holds the value of the "charge_id" field. ChargeID *string `json:"charge_id,omitempty"` + // LifecycleHandler holds the value of the "lifecycle_handler" field. + LifecycleHandler billing.LifecycleHandler `json:"lifecycle_handler,omitempty"` // LineIds holds the value of the "line_ids" field. // // Deprecated: invoice discounts are deprecated, use line_discounts instead @@ -334,7 +336,7 @@ func (*BillingInvoiceLine) scanValues(columns []string) ([]any, error) { values[i] = new([]byte) case billinginvoiceline.FieldAmount, billinginvoiceline.FieldTaxesTotal, billinginvoiceline.FieldTaxesInclusiveTotal, billinginvoiceline.FieldTaxesExclusiveTotal, billinginvoiceline.FieldChargesTotal, billinginvoiceline.FieldDiscountsTotal, billinginvoiceline.FieldCreditsTotal, billinginvoiceline.FieldTotal: values[i] = new(alpacadecimal.Decimal) - case billinginvoiceline.FieldID, billinginvoiceline.FieldNamespace, billinginvoiceline.FieldName, billinginvoiceline.FieldDescription, billinginvoiceline.FieldCurrency, billinginvoiceline.FieldInvoiceID, billinginvoiceline.FieldManagedBy, billinginvoiceline.FieldParentLineID, billinginvoiceline.FieldType, billinginvoiceline.FieldStatus, billinginvoiceline.FieldInvoicingAppExternalID, billinginvoiceline.FieldChildUniqueReferenceID, billinginvoiceline.FieldSubscriptionID, billinginvoiceline.FieldSubscriptionPhaseID, billinginvoiceline.FieldSubscriptionItemID, billinginvoiceline.FieldSplitLineGroupID, billinginvoiceline.FieldChargeID, billinginvoiceline.FieldLineIds: + case billinginvoiceline.FieldID, billinginvoiceline.FieldNamespace, billinginvoiceline.FieldName, billinginvoiceline.FieldDescription, billinginvoiceline.FieldCurrency, billinginvoiceline.FieldInvoiceID, billinginvoiceline.FieldManagedBy, billinginvoiceline.FieldParentLineID, billinginvoiceline.FieldType, billinginvoiceline.FieldStatus, billinginvoiceline.FieldInvoicingAppExternalID, billinginvoiceline.FieldChildUniqueReferenceID, billinginvoiceline.FieldSubscriptionID, billinginvoiceline.FieldSubscriptionPhaseID, billinginvoiceline.FieldSubscriptionItemID, billinginvoiceline.FieldSplitLineGroupID, billinginvoiceline.FieldChargeID, billinginvoiceline.FieldLifecycleHandler, billinginvoiceline.FieldLineIds: values[i] = new(sql.NullString) case billinginvoiceline.FieldCreatedAt, billinginvoiceline.FieldUpdatedAt, billinginvoiceline.FieldDeletedAt, billinginvoiceline.FieldPeriodStart, billinginvoiceline.FieldPeriodEnd, billinginvoiceline.FieldInvoiceAt, billinginvoiceline.FieldSubscriptionBillingPeriodFrom, billinginvoiceline.FieldSubscriptionBillingPeriodTo: values[i] = new(sql.NullTime) @@ -608,6 +610,12 @@ func (_m *BillingInvoiceLine) assignValues(columns []string, values []any) error _m.ChargeID = new(string) *_m.ChargeID = value.String } + case billinginvoiceline.FieldLifecycleHandler: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field lifecycle_handler", values[i]) + } else if value.Valid { + _m.LifecycleHandler = billing.LifecycleHandler(value.String) + } case billinginvoiceline.FieldLineIds: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field line_ids", values[i]) @@ -890,6 +898,9 @@ func (_m *BillingInvoiceLine) String() string { builder.WriteString(*v) } builder.WriteString(", ") + builder.WriteString("lifecycle_handler=") + builder.WriteString(fmt.Sprintf("%v", _m.LifecycleHandler)) + builder.WriteString(", ") if v := _m.LineIds; v != nil { builder.WriteString("line_ids=") builder.WriteString(*v) diff --git a/openmeter/ent/db/billinginvoiceline/billinginvoiceline.go b/openmeter/ent/db/billinginvoiceline/billinginvoiceline.go index b703f67631..bf82bdab99 100644 --- a/openmeter/ent/db/billinginvoiceline/billinginvoiceline.go +++ b/openmeter/ent/db/billinginvoiceline/billinginvoiceline.go @@ -91,6 +91,8 @@ const ( FieldSplitLineGroupID = "split_line_group_id" // FieldChargeID holds the string denoting the charge_id field in the database. FieldChargeID = "charge_id" + // FieldLifecycleHandler holds the string denoting the lifecycle_handler field in the database. + FieldLifecycleHandler = "lifecycle_handler" // FieldLineIds holds the string denoting the line_ids field in the database. FieldLineIds = "line_ids" // FieldCreditsApplied holds the string denoting the credits_applied field in the database. @@ -277,6 +279,7 @@ var Columns = []string{ FieldSubscriptionBillingPeriodTo, FieldSplitLineGroupID, FieldChargeID, + FieldLifecycleHandler, FieldCreditsApplied, } @@ -357,6 +360,18 @@ func StatusValidator(s billing.InvoiceLineStatus) error { } } +const DefaultLifecycleHandler billing.LifecycleHandler = "default" + +// LifecycleHandlerValidator is a validator for the "lifecycle_handler" field enum values. It is called by the builders before save. +func LifecycleHandlerValidator(lh billing.LifecycleHandler) error { + switch lh { + case "default", "charges": + return nil + default: + return fmt.Errorf("billinginvoiceline: invalid enum value for lifecycle_handler field: %q", lh) + } +} + // OrderOption defines the ordering options for the BillingInvoiceLine queries. type OrderOption func(*sql.Selector) @@ -535,6 +550,11 @@ func ByChargeID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldChargeID, opts...).ToFunc() } +// ByLifecycleHandler orders the results by the lifecycle_handler field. +func ByLifecycleHandler(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLifecycleHandler, opts...).ToFunc() +} + // ByLineIds orders the results by the line_ids field. func ByLineIds(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldLineIds, opts...).ToFunc() diff --git a/openmeter/ent/db/billinginvoiceline/where.go b/openmeter/ent/db/billinginvoiceline/where.go index bc9a948bdc..6f80a02df2 100644 --- a/openmeter/ent/db/billinginvoiceline/where.go +++ b/openmeter/ent/db/billinginvoiceline/where.go @@ -2028,6 +2028,36 @@ func ChargeIDContainsFold(v string) predicate.BillingInvoiceLine { return predicate.BillingInvoiceLine(sql.FieldContainsFold(FieldChargeID, v)) } +// LifecycleHandlerEQ applies the EQ predicate on the "lifecycle_handler" field. +func LifecycleHandlerEQ(v billing.LifecycleHandler) predicate.BillingInvoiceLine { + vc := v + return predicate.BillingInvoiceLine(sql.FieldEQ(FieldLifecycleHandler, vc)) +} + +// LifecycleHandlerNEQ applies the NEQ predicate on the "lifecycle_handler" field. +func LifecycleHandlerNEQ(v billing.LifecycleHandler) predicate.BillingInvoiceLine { + vc := v + return predicate.BillingInvoiceLine(sql.FieldNEQ(FieldLifecycleHandler, vc)) +} + +// LifecycleHandlerIn applies the In predicate on the "lifecycle_handler" field. +func LifecycleHandlerIn(vs ...billing.LifecycleHandler) predicate.BillingInvoiceLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceLine(sql.FieldIn(FieldLifecycleHandler, v...)) +} + +// LifecycleHandlerNotIn applies the NotIn predicate on the "lifecycle_handler" field. +func LifecycleHandlerNotIn(vs ...billing.LifecycleHandler) predicate.BillingInvoiceLine { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.BillingInvoiceLine(sql.FieldNotIn(FieldLifecycleHandler, v...)) +} + // LineIdsEQ applies the EQ predicate on the "line_ids" field. func LineIdsEQ(v string) predicate.BillingInvoiceLine { return predicate.BillingInvoiceLine(sql.FieldEQ(FieldLineIds, v)) diff --git a/openmeter/ent/db/billinginvoiceline_create.go b/openmeter/ent/db/billinginvoiceline_create.go index 3ea1eb950d..2dbff8cc9a 100644 --- a/openmeter/ent/db/billinginvoiceline_create.go +++ b/openmeter/ent/db/billinginvoiceline_create.go @@ -392,6 +392,20 @@ func (_c *BillingInvoiceLineCreate) SetNillableChargeID(v *string) *BillingInvoi return _c } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (_c *BillingInvoiceLineCreate) SetLifecycleHandler(v billing.LifecycleHandler) *BillingInvoiceLineCreate { + _c.mutation.SetLifecycleHandler(v) + return _c +} + +// SetNillableLifecycleHandler sets the "lifecycle_handler" field if the given value is not nil. +func (_c *BillingInvoiceLineCreate) SetNillableLifecycleHandler(v *billing.LifecycleHandler) *BillingInvoiceLineCreate { + if v != nil { + _c.SetLifecycleHandler(*v) + } + return _c +} + // SetLineIds sets the "line_ids" field. func (_c *BillingInvoiceLineCreate) SetLineIds(v string) *BillingInvoiceLineCreate { _c.mutation.SetLineIds(v) @@ -657,6 +671,10 @@ func (_c *BillingInvoiceLineCreate) defaults() { v := billinginvoiceline.DefaultUpdatedAt() _c.mutation.SetUpdatedAt(v) } + if _, ok := _c.mutation.LifecycleHandler(); !ok { + v := billinginvoiceline.DefaultLifecycleHandler + _c.mutation.SetLifecycleHandler(v) + } if _, ok := _c.mutation.ID(); !ok { v := billinginvoiceline.DefaultID() _c.mutation.SetID(v) @@ -755,6 +773,14 @@ func (_c *BillingInvoiceLineCreate) check() error { return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.status": %w`, err)} } } + if _, ok := _c.mutation.LifecycleHandler(); !ok { + return &ValidationError{Name: "lifecycle_handler", err: errors.New(`db: missing required field "BillingInvoiceLine.lifecycle_handler"`)} + } + if v, ok := _c.mutation.LifecycleHandler(); ok { + if err := billinginvoiceline.LifecycleHandlerValidator(v); err != nil { + return &ValidationError{Name: "lifecycle_handler", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.lifecycle_handler": %w`, err)} + } + } if v, ok := _c.mutation.CreditsApplied(); ok { if err := v.Validate(); err != nil { return &ValidationError{Name: "credits_applied", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.credits_applied": %w`, err)} @@ -926,6 +952,10 @@ func (_c *BillingInvoiceLineCreate) createSpec() (*BillingInvoiceLine, *sqlgraph _spec.SetField(billinginvoiceline.FieldSubscriptionBillingPeriodTo, field.TypeTime, value) _node.SubscriptionBillingPeriodTo = &value } + if value, ok := _c.mutation.LifecycleHandler(); ok { + _spec.SetField(billinginvoiceline.FieldLifecycleHandler, field.TypeEnum, value) + _node.LifecycleHandler = value + } if value, ok := _c.mutation.LineIds(); ok { _spec.SetField(billinginvoiceline.FieldLineIds, field.TypeString, value) _node.LineIds = &value @@ -1753,6 +1783,18 @@ func (u *BillingInvoiceLineUpsert) ClearChargeID() *BillingInvoiceLineUpsert { return u } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (u *BillingInvoiceLineUpsert) SetLifecycleHandler(v billing.LifecycleHandler) *BillingInvoiceLineUpsert { + u.Set(billinginvoiceline.FieldLifecycleHandler, v) + return u +} + +// UpdateLifecycleHandler sets the "lifecycle_handler" field to the value that was provided on create. +func (u *BillingInvoiceLineUpsert) UpdateLifecycleHandler() *BillingInvoiceLineUpsert { + u.SetExcluded(billinginvoiceline.FieldLifecycleHandler) + return u +} + // SetLineIds sets the "line_ids" field. func (u *BillingInvoiceLineUpsert) SetLineIds(v string) *BillingInvoiceLineUpsert { u.Set(billinginvoiceline.FieldLineIds, v) @@ -2430,6 +2472,20 @@ func (u *BillingInvoiceLineUpsertOne) ClearChargeID() *BillingInvoiceLineUpsertO }) } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (u *BillingInvoiceLineUpsertOne) SetLifecycleHandler(v billing.LifecycleHandler) *BillingInvoiceLineUpsertOne { + return u.Update(func(s *BillingInvoiceLineUpsert) { + s.SetLifecycleHandler(v) + }) +} + +// UpdateLifecycleHandler sets the "lifecycle_handler" field to the value that was provided on create. +func (u *BillingInvoiceLineUpsertOne) UpdateLifecycleHandler() *BillingInvoiceLineUpsertOne { + return u.Update(func(s *BillingInvoiceLineUpsert) { + s.UpdateLifecycleHandler() + }) +} + // SetLineIds sets the "line_ids" field. func (u *BillingInvoiceLineUpsertOne) SetLineIds(v string) *BillingInvoiceLineUpsertOne { return u.Update(func(s *BillingInvoiceLineUpsert) { @@ -3283,6 +3339,20 @@ func (u *BillingInvoiceLineUpsertBulk) ClearChargeID() *BillingInvoiceLineUpsert }) } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (u *BillingInvoiceLineUpsertBulk) SetLifecycleHandler(v billing.LifecycleHandler) *BillingInvoiceLineUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUpsert) { + s.SetLifecycleHandler(v) + }) +} + +// UpdateLifecycleHandler sets the "lifecycle_handler" field to the value that was provided on create. +func (u *BillingInvoiceLineUpsertBulk) UpdateLifecycleHandler() *BillingInvoiceLineUpsertBulk { + return u.Update(func(s *BillingInvoiceLineUpsert) { + s.UpdateLifecycleHandler() + }) +} + // SetLineIds sets the "line_ids" field. func (u *BillingInvoiceLineUpsertBulk) SetLineIds(v string) *BillingInvoiceLineUpsertBulk { return u.Update(func(s *BillingInvoiceLineUpsert) { diff --git a/openmeter/ent/db/billinginvoiceline_update.go b/openmeter/ent/db/billinginvoiceline_update.go index 280c8dd49e..496437bcc7 100644 --- a/openmeter/ent/db/billinginvoiceline_update.go +++ b/openmeter/ent/db/billinginvoiceline_update.go @@ -578,6 +578,20 @@ func (_u *BillingInvoiceLineUpdate) ClearChargeID() *BillingInvoiceLineUpdate { return _u } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (_u *BillingInvoiceLineUpdate) SetLifecycleHandler(v billing.LifecycleHandler) *BillingInvoiceLineUpdate { + _u.mutation.SetLifecycleHandler(v) + return _u +} + +// SetNillableLifecycleHandler sets the "lifecycle_handler" field if the given value is not nil. +func (_u *BillingInvoiceLineUpdate) SetNillableLifecycleHandler(v *billing.LifecycleHandler) *BillingInvoiceLineUpdate { + if v != nil { + _u.SetLifecycleHandler(*v) + } + return _u +} + // SetLineIds sets the "line_ids" field. func (_u *BillingInvoiceLineUpdate) SetLineIds(v string) *BillingInvoiceLineUpdate { _u.mutation.SetLineIds(v) @@ -1042,6 +1056,11 @@ func (_u *BillingInvoiceLineUpdate) check() error { return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.status": %w`, err)} } } + if v, ok := _u.mutation.LifecycleHandler(); ok { + if err := billinginvoiceline.LifecycleHandlerValidator(v); err != nil { + return &ValidationError{Name: "lifecycle_handler", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.lifecycle_handler": %w`, err)} + } + } if v, ok := _u.mutation.CreditsApplied(); ok { if err := v.Validate(); err != nil { return &ValidationError{Name: "credits_applied", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.credits_applied": %w`, err)} @@ -1180,6 +1199,9 @@ func (_u *BillingInvoiceLineUpdate) sqlSave(ctx context.Context) (_node int, err if _u.mutation.SubscriptionBillingPeriodToCleared() { _spec.ClearField(billinginvoiceline.FieldSubscriptionBillingPeriodTo, field.TypeTime) } + if value, ok := _u.mutation.LifecycleHandler(); ok { + _spec.SetField(billinginvoiceline.FieldLifecycleHandler, field.TypeEnum, value) + } if value, ok := _u.mutation.LineIds(); ok { _spec.SetField(billinginvoiceline.FieldLineIds, field.TypeString, value) } @@ -2308,6 +2330,20 @@ func (_u *BillingInvoiceLineUpdateOne) ClearChargeID() *BillingInvoiceLineUpdate return _u } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (_u *BillingInvoiceLineUpdateOne) SetLifecycleHandler(v billing.LifecycleHandler) *BillingInvoiceLineUpdateOne { + _u.mutation.SetLifecycleHandler(v) + return _u +} + +// SetNillableLifecycleHandler sets the "lifecycle_handler" field if the given value is not nil. +func (_u *BillingInvoiceLineUpdateOne) SetNillableLifecycleHandler(v *billing.LifecycleHandler) *BillingInvoiceLineUpdateOne { + if v != nil { + _u.SetLifecycleHandler(*v) + } + return _u +} + // SetLineIds sets the "line_ids" field. func (_u *BillingInvoiceLineUpdateOne) SetLineIds(v string) *BillingInvoiceLineUpdateOne { _u.mutation.SetLineIds(v) @@ -2785,6 +2821,11 @@ func (_u *BillingInvoiceLineUpdateOne) check() error { return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.status": %w`, err)} } } + if v, ok := _u.mutation.LifecycleHandler(); ok { + if err := billinginvoiceline.LifecycleHandlerValidator(v); err != nil { + return &ValidationError{Name: "lifecycle_handler", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.lifecycle_handler": %w`, err)} + } + } if v, ok := _u.mutation.CreditsApplied(); ok { if err := v.Validate(); err != nil { return &ValidationError{Name: "credits_applied", err: fmt.Errorf(`db: validator failed for field "BillingInvoiceLine.credits_applied": %w`, err)} @@ -2940,6 +2981,9 @@ func (_u *BillingInvoiceLineUpdateOne) sqlSave(ctx context.Context) (_node *Bill if _u.mutation.SubscriptionBillingPeriodToCleared() { _spec.ClearField(billinginvoiceline.FieldSubscriptionBillingPeriodTo, field.TypeTime) } + if value, ok := _u.mutation.LifecycleHandler(); ok { + _spec.SetField(billinginvoiceline.FieldLifecycleHandler, field.TypeEnum, value) + } if value, ok := _u.mutation.LineIds(); ok { _spec.SetField(billinginvoiceline.FieldLineIds, field.TypeString, value) } diff --git a/openmeter/ent/db/charge.go b/openmeter/ent/db/charge.go index 00a00a2995..919a2c4040 100644 --- a/openmeter/ent/db/charge.go +++ b/openmeter/ent/db/charge.go @@ -15,6 +15,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/charge" "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" @@ -86,6 +87,8 @@ type ChargeEdges struct { FlatFee *ChargeFlatFee `json:"flat_fee,omitempty"` // CreditPurchase holds the value of the credit_purchase edge. CreditPurchase *ChargeCreditPurchase `json:"credit_purchase,omitempty"` + // UsageBased holds the value of the usage_based edge. + UsageBased *ChargeUsageBased `json:"usage_based,omitempty"` // BillingInvoiceLines holds the value of the billing_invoice_lines edge. BillingInvoiceLines []*BillingInvoiceLine `json:"billing_invoice_lines,omitempty"` // BillingSplitLineGroups holds the value of the billing_split_line_groups edge. @@ -100,7 +103,7 @@ type ChargeEdges struct { SubscriptionItem *SubscriptionItem `json:"subscription_item,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [8]bool + loadedTypes [9]bool } // FlatFeeOrErr returns the FlatFee value or an error if the edge @@ -125,10 +128,21 @@ func (e ChargeEdges) CreditPurchaseOrErr() (*ChargeCreditPurchase, error) { return nil, &NotLoadedError{edge: "credit_purchase"} } +// UsageBasedOrErr returns the UsageBased value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeEdges) UsageBasedOrErr() (*ChargeUsageBased, error) { + if e.UsageBased != nil { + return e.UsageBased, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: chargeusagebased.Label} + } + return nil, &NotLoadedError{edge: "usage_based"} +} + // BillingInvoiceLinesOrErr returns the BillingInvoiceLines value or an error if the edge // was not loaded in eager-loading. func (e ChargeEdges) BillingInvoiceLinesOrErr() ([]*BillingInvoiceLine, error) { - if e.loadedTypes[2] { + if e.loadedTypes[3] { return e.BillingInvoiceLines, nil } return nil, &NotLoadedError{edge: "billing_invoice_lines"} @@ -137,7 +151,7 @@ func (e ChargeEdges) BillingInvoiceLinesOrErr() ([]*BillingInvoiceLine, error) { // BillingSplitLineGroupsOrErr returns the BillingSplitLineGroups value or an error if the edge // was not loaded in eager-loading. func (e ChargeEdges) BillingSplitLineGroupsOrErr() ([]*BillingInvoiceSplitLineGroup, error) { - if e.loadedTypes[3] { + if e.loadedTypes[4] { return e.BillingSplitLineGroups, nil } return nil, &NotLoadedError{edge: "billing_split_line_groups"} @@ -148,7 +162,7 @@ func (e ChargeEdges) BillingSplitLineGroupsOrErr() ([]*BillingInvoiceSplitLineGr func (e ChargeEdges) CustomerOrErr() (*Customer, error) { if e.Customer != nil { return e.Customer, nil - } else if e.loadedTypes[4] { + } else if e.loadedTypes[5] { return nil, &NotFoundError{label: customer.Label} } return nil, &NotLoadedError{edge: "customer"} @@ -159,7 +173,7 @@ func (e ChargeEdges) CustomerOrErr() (*Customer, error) { func (e ChargeEdges) SubscriptionOrErr() (*Subscription, error) { if e.Subscription != nil { return e.Subscription, nil - } else if e.loadedTypes[5] { + } else if e.loadedTypes[6] { return nil, &NotFoundError{label: subscription.Label} } return nil, &NotLoadedError{edge: "subscription"} @@ -170,7 +184,7 @@ func (e ChargeEdges) SubscriptionOrErr() (*Subscription, error) { func (e ChargeEdges) SubscriptionPhaseOrErr() (*SubscriptionPhase, error) { if e.SubscriptionPhase != nil { return e.SubscriptionPhase, nil - } else if e.loadedTypes[6] { + } else if e.loadedTypes[7] { return nil, &NotFoundError{label: subscriptionphase.Label} } return nil, &NotLoadedError{edge: "subscription_phase"} @@ -181,7 +195,7 @@ func (e ChargeEdges) SubscriptionPhaseOrErr() (*SubscriptionPhase, error) { func (e ChargeEdges) SubscriptionItemOrErr() (*SubscriptionItem, error) { if e.SubscriptionItem != nil { return e.SubscriptionItem, nil - } else if e.loadedTypes[7] { + } else if e.loadedTypes[8] { return nil, &NotFoundError{label: subscriptionitem.Label} } return nil, &NotLoadedError{edge: "subscription_item"} @@ -390,6 +404,11 @@ func (_m *Charge) QueryCreditPurchase() *ChargeCreditPurchaseQuery { return NewChargeClient(_m.config).QueryCreditPurchase(_m) } +// QueryUsageBased queries the "usage_based" edge of the Charge entity. +func (_m *Charge) QueryUsageBased() *ChargeUsageBasedQuery { + return NewChargeClient(_m.config).QueryUsageBased(_m) +} + // QueryBillingInvoiceLines queries the "billing_invoice_lines" edge of the Charge entity. func (_m *Charge) QueryBillingInvoiceLines() *BillingInvoiceLineQuery { return NewChargeClient(_m.config).QueryBillingInvoiceLines(_m) diff --git a/openmeter/ent/db/charge/charge.go b/openmeter/ent/db/charge/charge.go index 6af5942f3a..61fe4d283b 100644 --- a/openmeter/ent/db/charge/charge.go +++ b/openmeter/ent/db/charge/charge.go @@ -67,6 +67,8 @@ const ( EdgeFlatFee = "flat_fee" // EdgeCreditPurchase holds the string denoting the credit_purchase edge name in mutations. EdgeCreditPurchase = "credit_purchase" + // EdgeUsageBased holds the string denoting the usage_based edge name in mutations. + EdgeUsageBased = "usage_based" // EdgeBillingInvoiceLines holds the string denoting the billing_invoice_lines edge name in mutations. EdgeBillingInvoiceLines = "billing_invoice_lines" // EdgeBillingSplitLineGroups holds the string denoting the billing_split_line_groups edge name in mutations. @@ -95,6 +97,13 @@ const ( CreditPurchaseInverseTable = "charge_credit_purchases" // CreditPurchaseColumn is the table column denoting the credit_purchase relation/edge. CreditPurchaseColumn = "id" + // UsageBasedTable is the table that holds the usage_based relation/edge. + UsageBasedTable = "charge_usage_based" + // UsageBasedInverseTable is the table name for the ChargeUsageBased entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebased" package. + UsageBasedInverseTable = "charge_usage_based" + // UsageBasedColumn is the table column denoting the usage_based relation/edge. + UsageBasedColumn = "id" // BillingInvoiceLinesTable is the table that holds the billing_invoice_lines relation/edge. BillingInvoiceLinesTable = "billing_invoice_lines" // BillingInvoiceLinesInverseTable is the table name for the BillingInvoiceLine entity. @@ -351,6 +360,13 @@ func ByCreditPurchaseField(field string, opts ...sql.OrderTermOption) OrderOptio } } +// ByUsageBasedField orders the results by usage_based field. +func ByUsageBasedField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsageBasedStep(), sql.OrderByField(field, opts...)) + } +} + // ByBillingInvoiceLinesCount orders the results by billing_invoice_lines count. func ByBillingInvoiceLinesCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -420,6 +436,13 @@ func newCreditPurchaseStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2O, false, CreditPurchaseTable, CreditPurchaseColumn), ) } +func newUsageBasedStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageBasedInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, UsageBasedTable, UsageBasedColumn), + ) +} func newBillingInvoiceLinesStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/openmeter/ent/db/charge/where.go b/openmeter/ent/db/charge/where.go index 4e382d30b1..89944bcddf 100644 --- a/openmeter/ent/db/charge/where.go +++ b/openmeter/ent/db/charge/where.go @@ -1339,6 +1339,29 @@ func HasCreditPurchaseWith(preds ...predicate.ChargeCreditPurchase) predicate.Ch }) } +// HasUsageBased applies the HasEdge predicate on the "usage_based" edge. +func HasUsageBased() predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, UsageBasedTable, UsageBasedColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsageBasedWith applies the HasEdge predicate on the "usage_based" edge with a given conditions (other predicates). +func HasUsageBasedWith(preds ...predicate.ChargeUsageBased) predicate.Charge { + return predicate.Charge(func(s *sql.Selector) { + step := newUsageBasedStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasBillingInvoiceLines applies the HasEdge predicate on the "billing_invoice_lines" edge. func HasBillingInvoiceLines() predicate.Charge { return predicate.Charge(func(s *sql.Selector) { diff --git a/openmeter/ent/db/charge_create.go b/openmeter/ent/db/charge_create.go index 90250b310d..e01d6a9017 100644 --- a/openmeter/ent/db/charge_create.go +++ b/openmeter/ent/db/charge_create.go @@ -19,6 +19,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/charge" "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" "github.com/openmeterio/openmeter/openmeter/ent/db/subscriptionitem" @@ -289,6 +290,25 @@ func (_c *ChargeCreate) SetCreditPurchase(v *ChargeCreditPurchase) *ChargeCreate return _c.SetCreditPurchaseID(v.ID) } +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID. +func (_c *ChargeCreate) SetUsageBasedID(id string) *ChargeCreate { + _c.mutation.SetUsageBasedID(id) + return _c +} + +// SetNillableUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID if the given value is not nil. +func (_c *ChargeCreate) SetNillableUsageBasedID(id *string) *ChargeCreate { + if id != nil { + _c = _c.SetUsageBasedID(*id) + } + return _c +} + +// SetUsageBased sets the "usage_based" edge to the ChargeUsageBased entity. +func (_c *ChargeCreate) SetUsageBased(v *ChargeUsageBased) *ChargeCreate { + return _c.SetUsageBasedID(v.ID) +} + // AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. func (_c *ChargeCreate) AddBillingInvoiceLineIDs(ids ...string) *ChargeCreate { _c.mutation.AddBillingInvoiceLineIDs(ids...) @@ -612,6 +632,22 @@ func (_c *ChargeCreate) createSpec() (*Charge, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.UsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: charge.UsageBasedTable, + Columns: []string{charge.UsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := _c.mutation.BillingInvoiceLinesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/openmeter/ent/db/charge_query.go b/openmeter/ent/db/charge_query.go index 3c06cffdb6..f041911937 100644 --- a/openmeter/ent/db/charge_query.go +++ b/openmeter/ent/db/charge_query.go @@ -18,6 +18,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/charge" "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" "github.com/openmeterio/openmeter/openmeter/ent/db/subscription" @@ -34,6 +35,7 @@ type ChargeQuery struct { predicates []predicate.Charge withFlatFee *ChargeFlatFeeQuery withCreditPurchase *ChargeCreditPurchaseQuery + withUsageBased *ChargeUsageBasedQuery withBillingInvoiceLines *BillingInvoiceLineQuery withBillingSplitLineGroups *BillingInvoiceSplitLineGroupQuery withCustomer *CustomerQuery @@ -121,6 +123,28 @@ func (_q *ChargeQuery) QueryCreditPurchase() *ChargeCreditPurchaseQuery { return query } +// QueryUsageBased chains the current query on the "usage_based" edge. +func (_q *ChargeQuery) QueryUsageBased() *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(charge.Table, charge.FieldID, selector), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, charge.UsageBasedTable, charge.UsageBasedColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryBillingInvoiceLines chains the current query on the "billing_invoice_lines" edge. func (_q *ChargeQuery) QueryBillingInvoiceLines() *BillingInvoiceLineQuery { query := (&BillingInvoiceLineClient{config: _q.config}).Query() @@ -447,6 +471,7 @@ func (_q *ChargeQuery) Clone() *ChargeQuery { predicates: append([]predicate.Charge{}, _q.predicates...), withFlatFee: _q.withFlatFee.Clone(), withCreditPurchase: _q.withCreditPurchase.Clone(), + withUsageBased: _q.withUsageBased.Clone(), withBillingInvoiceLines: _q.withBillingInvoiceLines.Clone(), withBillingSplitLineGroups: _q.withBillingSplitLineGroups.Clone(), withCustomer: _q.withCustomer.Clone(), @@ -481,6 +506,17 @@ func (_q *ChargeQuery) WithCreditPurchase(opts ...func(*ChargeCreditPurchaseQuer return _q } +// WithUsageBased tells the query-builder to eager-load the nodes that are connected to +// the "usage_based" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeQuery) WithUsageBased(opts ...func(*ChargeUsageBasedQuery)) *ChargeQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUsageBased = query + return _q +} + // WithBillingInvoiceLines tells the query-builder to eager-load the nodes that are connected to // the "billing_invoice_lines" edge. The optional arguments are used to configure the query builder of the edge. func (_q *ChargeQuery) WithBillingInvoiceLines(opts ...func(*BillingInvoiceLineQuery)) *ChargeQuery { @@ -625,9 +661,10 @@ func (_q *ChargeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Charg var ( nodes = []*Charge{} _spec = _q.querySpec() - loadedTypes = [8]bool{ + loadedTypes = [9]bool{ _q.withFlatFee != nil, _q.withCreditPurchase != nil, + _q.withUsageBased != nil, _q.withBillingInvoiceLines != nil, _q.withBillingSplitLineGroups != nil, _q.withCustomer != nil, @@ -669,6 +706,12 @@ func (_q *ChargeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Charg return nil, err } } + if query := _q.withUsageBased; query != nil { + if err := _q.loadUsageBased(ctx, query, nodes, nil, + func(n *Charge, e *ChargeUsageBased) { n.Edges.UsageBased = e }); err != nil { + return nil, err + } + } if query := _q.withBillingInvoiceLines; query != nil { if err := _q.loadBillingInvoiceLines(ctx, query, nodes, func(n *Charge) { n.Edges.BillingInvoiceLines = []*BillingInvoiceLine{} }, @@ -762,6 +805,30 @@ func (_q *ChargeQuery) loadCreditPurchase(ctx context.Context, query *ChargeCred } return nil } +func (_q *ChargeQuery) loadUsageBased(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *ChargeUsageBased)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Charge) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + } + query.Where(predicate.ChargeUsageBased(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(charge.UsageBasedColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *ChargeQuery) loadBillingInvoiceLines(ctx context.Context, query *BillingInvoiceLineQuery, nodes []*Charge, init func(*Charge), assign func(*Charge, *BillingInvoiceLine)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[string]*Charge) diff --git a/openmeter/ent/db/charge_update.go b/openmeter/ent/db/charge_update.go index 9856d35cab..8eb15ef5ba 100644 --- a/openmeter/ent/db/charge_update.go +++ b/openmeter/ent/db/charge_update.go @@ -18,6 +18,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/charge" "github.com/openmeterio/openmeter/openmeter/ent/db/chargecreditpurchase" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfee" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" "github.com/openmeterio/openmeter/pkg/models" ) @@ -289,6 +290,25 @@ func (_u *ChargeUpdate) SetCreditPurchase(v *ChargeCreditPurchase) *ChargeUpdate return _u.SetCreditPurchaseID(v.ID) } +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID. +func (_u *ChargeUpdate) SetUsageBasedID(id string) *ChargeUpdate { + _u.mutation.SetUsageBasedID(id) + return _u +} + +// SetNillableUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID if the given value is not nil. +func (_u *ChargeUpdate) SetNillableUsageBasedID(id *string) *ChargeUpdate { + if id != nil { + _u = _u.SetUsageBasedID(*id) + } + return _u +} + +// SetUsageBased sets the "usage_based" edge to the ChargeUsageBased entity. +func (_u *ChargeUpdate) SetUsageBased(v *ChargeUsageBased) *ChargeUpdate { + return _u.SetUsageBasedID(v.ID) +} + // AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. func (_u *ChargeUpdate) AddBillingInvoiceLineIDs(ids ...string) *ChargeUpdate { _u.mutation.AddBillingInvoiceLineIDs(ids...) @@ -336,6 +356,12 @@ func (_u *ChargeUpdate) ClearCreditPurchase() *ChargeUpdate { return _u } +// ClearUsageBased clears the "usage_based" edge to the ChargeUsageBased entity. +func (_u *ChargeUpdate) ClearUsageBased() *ChargeUpdate { + _u.mutation.ClearUsageBased() + return _u +} + // ClearBillingInvoiceLines clears all "billing_invoice_lines" edges to the BillingInvoiceLine entity. func (_u *ChargeUpdate) ClearBillingInvoiceLines() *ChargeUpdate { _u.mutation.ClearBillingInvoiceLines() @@ -562,6 +588,35 @@ func (_u *ChargeUpdate) sqlSave(ctx context.Context) (_node int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.UsageBasedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: charge.UsageBasedTable, + Columns: []string{charge.UsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: charge.UsageBasedTable, + Columns: []string{charge.UsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.BillingInvoiceLinesCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -926,6 +981,25 @@ func (_u *ChargeUpdateOne) SetCreditPurchase(v *ChargeCreditPurchase) *ChargeUpd return _u.SetCreditPurchaseID(v.ID) } +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID. +func (_u *ChargeUpdateOne) SetUsageBasedID(id string) *ChargeUpdateOne { + _u.mutation.SetUsageBasedID(id) + return _u +} + +// SetNillableUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID if the given value is not nil. +func (_u *ChargeUpdateOne) SetNillableUsageBasedID(id *string) *ChargeUpdateOne { + if id != nil { + _u = _u.SetUsageBasedID(*id) + } + return _u +} + +// SetUsageBased sets the "usage_based" edge to the ChargeUsageBased entity. +func (_u *ChargeUpdateOne) SetUsageBased(v *ChargeUsageBased) *ChargeUpdateOne { + return _u.SetUsageBasedID(v.ID) +} + // AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by IDs. func (_u *ChargeUpdateOne) AddBillingInvoiceLineIDs(ids ...string) *ChargeUpdateOne { _u.mutation.AddBillingInvoiceLineIDs(ids...) @@ -973,6 +1047,12 @@ func (_u *ChargeUpdateOne) ClearCreditPurchase() *ChargeUpdateOne { return _u } +// ClearUsageBased clears the "usage_based" edge to the ChargeUsageBased entity. +func (_u *ChargeUpdateOne) ClearUsageBased() *ChargeUpdateOne { + _u.mutation.ClearUsageBased() + return _u +} + // ClearBillingInvoiceLines clears all "billing_invoice_lines" edges to the BillingInvoiceLine entity. func (_u *ChargeUpdateOne) ClearBillingInvoiceLines() *ChargeUpdateOne { _u.mutation.ClearBillingInvoiceLines() @@ -1229,6 +1309,35 @@ func (_u *ChargeUpdateOne) sqlSave(ctx context.Context) (_node *Charge, err erro } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.UsageBasedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: charge.UsageBasedTable, + Columns: []string{charge.UsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: charge.UsageBasedTable, + Columns: []string{charge.UsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.BillingInvoiceLinesCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/openmeter/ent/db/chargeusagebased.go b/openmeter/ent/db/chargeusagebased.go new file mode 100644 index 0000000000..9cdf65c312 --- /dev/null +++ b/openmeter/ent/db/chargeusagebased.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// ChargeUsageBased is the model entity for the ChargeUsageBased schema. +type ChargeUsageBased struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // InvoiceAt holds the value of the "invoice_at" field. + InvoiceAt time.Time `json:"invoice_at,omitempty"` + // SettlementMode holds the value of the "settlement_mode" field. + SettlementMode productcatalog.SettlementMode `json:"settlement_mode,omitempty"` + // Discounts holds the value of the "discounts" field. + Discounts *productcatalog.Discounts `json:"discounts,omitempty"` + // FeatureKey holds the value of the "feature_key" field. + FeatureKey string `json:"feature_key,omitempty"` + // Price holds the value of the "price" field. + Price *productcatalog.Price `json:"price,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedQuery when eager-loading is set. + Edges ChargeUsageBasedEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedEdges struct { + // Charge holds the value of the charge edge. + Charge *Charge `json:"charge,omitempty"` + // Runs holds the value of the runs edge. + Runs []*ChargeUsageBasedRuns `json:"runs,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// ChargeOrErr returns the Charge value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedEdges) ChargeOrErr() (*Charge, error) { + if e.Charge != nil { + return e.Charge, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: charge.Label} + } + return nil, &NotLoadedError{edge: "charge"} +} + +// RunsOrErr returns the Runs value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeUsageBasedEdges) RunsOrErr() ([]*ChargeUsageBasedRuns, error) { + if e.loadedTypes[1] { + return e.Runs, nil + } + return nil, &NotLoadedError{edge: "runs"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBased) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebased.FieldID, chargeusagebased.FieldNamespace, chargeusagebased.FieldSettlementMode, chargeusagebased.FieldFeatureKey: + values[i] = new(sql.NullString) + case chargeusagebased.FieldInvoiceAt: + values[i] = new(sql.NullTime) + case chargeusagebased.FieldDiscounts: + values[i] = chargeusagebased.ValueScanner.Discounts.ScanValue() + case chargeusagebased.FieldPrice: + values[i] = chargeusagebased.ValueScanner.Price.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeUsageBased fields. +func (_m *ChargeUsageBased) 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) + } + for i := range columns { + switch columns[i] { + case chargeusagebased.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case chargeusagebased.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + _m.Namespace = value.String + } + case chargeusagebased.FieldInvoiceAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field invoice_at", values[i]) + } else if value.Valid { + _m.InvoiceAt = value.Time + } + case chargeusagebased.FieldSettlementMode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field settlement_mode", values[i]) + } else if value.Valid { + _m.SettlementMode = productcatalog.SettlementMode(value.String) + } + case chargeusagebased.FieldDiscounts: + if value, err := chargeusagebased.ValueScanner.Discounts.FromValue(values[i]); err != nil { + return err + } else { + _m.Discounts = value + } + case chargeusagebased.FieldFeatureKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field feature_key", values[i]) + } else if value.Valid { + _m.FeatureKey = value.String + } + case chargeusagebased.FieldPrice: + if value, err := chargeusagebased.ValueScanner.Price.FromValue(values[i]); err != nil { + return err + } else { + _m.Price = value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeUsageBased. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBased) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryCharge queries the "charge" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryCharge() *ChargeQuery { + return NewChargeUsageBasedClient(_m.config).QueryCharge(_m) +} + +// QueryRuns queries the "runs" edge of the ChargeUsageBased entity. +func (_m *ChargeUsageBased) QueryRuns() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedClient(_m.config).QueryRuns(_m) +} + +// Update returns a builder for updating this ChargeUsageBased. +// Note that you need to call ChargeUsageBased.Unwrap() before calling this method if this ChargeUsageBased +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBased) Update() *ChargeUsageBasedUpdateOne { + return NewChargeUsageBasedClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBased 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 (_m *ChargeUsageBased) Unwrap() *ChargeUsageBased { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBased is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBased) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBased(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("invoice_at=") + builder.WriteString(_m.InvoiceAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("settlement_mode=") + builder.WriteString(fmt.Sprintf("%v", _m.SettlementMode)) + builder.WriteString(", ") + if v := _m.Discounts; v != nil { + builder.WriteString("discounts=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("feature_key=") + builder.WriteString(_m.FeatureKey) + builder.WriteString(", ") + builder.WriteString("price=") + builder.WriteString(fmt.Sprintf("%v", _m.Price)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBaseds is a parsable slice of ChargeUsageBased. +type ChargeUsageBaseds []*ChargeUsageBased diff --git a/openmeter/ent/db/chargeusagebased/chargeusagebased.go b/openmeter/ent/db/chargeusagebased/chargeusagebased.go new file mode 100644 index 0000000000..7f9f9f58be --- /dev/null +++ b/openmeter/ent/db/chargeusagebased/chargeusagebased.go @@ -0,0 +1,169 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebased + +import ( + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +const ( + // Label holds the string label denoting the chargeusagebased type in the database. + Label = "charge_usage_based" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldInvoiceAt holds the string denoting the invoice_at field in the database. + FieldInvoiceAt = "invoice_at" + // FieldSettlementMode holds the string denoting the settlement_mode field in the database. + FieldSettlementMode = "settlement_mode" + // FieldDiscounts holds the string denoting the discounts field in the database. + FieldDiscounts = "discounts" + // FieldFeatureKey holds the string denoting the feature_key field in the database. + FieldFeatureKey = "feature_key" + // FieldPrice holds the string denoting the price field in the database. + FieldPrice = "price" + // EdgeCharge holds the string denoting the charge edge name in mutations. + EdgeCharge = "charge" + // EdgeRuns holds the string denoting the runs edge name in mutations. + EdgeRuns = "runs" + // Table holds the table name of the chargeusagebased in the database. + Table = "charge_usage_based" + // ChargeTable is the table that holds the charge relation/edge. + ChargeTable = "charge_usage_based" + // ChargeInverseTable is the table name for the Charge entity. + // It exists in this package in order to avoid circular dependency with the "charge" package. + ChargeInverseTable = "charges" + // ChargeColumn is the table column denoting the charge relation/edge. + ChargeColumn = "id" + // RunsTable is the table that holds the runs relation/edge. + RunsTable = "charge_usage_based_runs" + // RunsInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + RunsInverseTable = "charge_usage_based_runs" + // RunsColumn is the table column denoting the runs relation/edge. + RunsColumn = "charge_id" +) + +// Columns holds all SQL columns for chargeusagebased fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldInvoiceAt, + FieldSettlementMode, + FieldDiscounts, + FieldFeatureKey, + FieldPrice, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // FeatureKeyValidator is a validator for the "feature_key" field. It is called by the builders before save. + FeatureKeyValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string + // ValueScanner of all ChargeUsageBased fields. + ValueScanner struct { + Discounts field.TypeValueScanner[*productcatalog.Discounts] + Price field.TypeValueScanner[*productcatalog.Price] + } +) + +// SettlementModeValidator is a validator for the "settlement_mode" field enum values. It is called by the builders before save. +func SettlementModeValidator(sm productcatalog.SettlementMode) error { + switch sm { + case "invoice_only", "credit_then_invoice", "credit_only": + return nil + default: + return fmt.Errorf("chargeusagebased: invalid enum value for settlement_mode field: %q", sm) + } +} + +// OrderOption defines the ordering options for the ChargeUsageBased 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() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByInvoiceAt orders the results by the invoice_at field. +func ByInvoiceAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInvoiceAt, opts...).ToFunc() +} + +// BySettlementMode orders the results by the settlement_mode field. +func BySettlementMode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSettlementMode, opts...).ToFunc() +} + +// ByDiscounts orders the results by the discounts field. +func ByDiscounts(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDiscounts, opts...).ToFunc() +} + +// ByFeatureKey orders the results by the feature_key field. +func ByFeatureKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFeatureKey, opts...).ToFunc() +} + +// ByPrice orders the results by the price field. +func ByPrice(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPrice, opts...).ToFunc() +} + +// ByChargeField orders the results by charge field. +func ByChargeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChargeStep(), sql.OrderByField(field, opts...)) + } +} + +// ByRunsCount orders the results by runs count. +func ByRunsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newRunsStep(), opts...) + } +} + +// ByRuns orders the results by runs terms. +func ByRuns(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRunsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newChargeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChargeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, ChargeTable, ChargeColumn), + ) +} +func newRunsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RunsTable, RunsColumn), + ) +} diff --git a/openmeter/ent/db/chargeusagebased/where.go b/openmeter/ent/db/chargeusagebased/where.go new file mode 100644 index 0000000000..552e277a2b --- /dev/null +++ b/openmeter/ent/db/chargeusagebased/where.go @@ -0,0 +1,353 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebased + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldNamespace, v)) +} + +// InvoiceAt applies equality check predicate on the "invoice_at" field. It's identical to InvoiceAtEQ. +func InvoiceAt(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// FeatureKey applies equality check predicate on the "feature_key" field. It's identical to FeatureKeyEQ. +func FeatureKey(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFeatureKey, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldNamespace, v)) +} + +// InvoiceAtEQ applies the EQ predicate on the "invoice_at" field. +func InvoiceAtEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtNEQ applies the NEQ predicate on the "invoice_at" field. +func InvoiceAtNEQ(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldInvoiceAt, v)) +} + +// InvoiceAtIn applies the In predicate on the "invoice_at" field. +func InvoiceAtIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtNotIn applies the NotIn predicate on the "invoice_at" field. +func InvoiceAtNotIn(vs ...time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldInvoiceAt, vs...)) +} + +// InvoiceAtGT applies the GT predicate on the "invoice_at" field. +func InvoiceAtGT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldInvoiceAt, v)) +} + +// InvoiceAtGTE applies the GTE predicate on the "invoice_at" field. +func InvoiceAtGTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldInvoiceAt, v)) +} + +// InvoiceAtLT applies the LT predicate on the "invoice_at" field. +func InvoiceAtLT(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldInvoiceAt, v)) +} + +// InvoiceAtLTE applies the LTE predicate on the "invoice_at" field. +func InvoiceAtLTE(v time.Time) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldInvoiceAt, v)) +} + +// SettlementModeEQ applies the EQ predicate on the "settlement_mode" field. +func SettlementModeEQ(v productcatalog.SettlementMode) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldEQ(FieldSettlementMode, vc)) +} + +// SettlementModeNEQ applies the NEQ predicate on the "settlement_mode" field. +func SettlementModeNEQ(v productcatalog.SettlementMode) predicate.ChargeUsageBased { + vc := v + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldSettlementMode, vc)) +} + +// SettlementModeIn applies the In predicate on the "settlement_mode" field. +func SettlementModeIn(vs ...productcatalog.SettlementMode) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldIn(FieldSettlementMode, v...)) +} + +// SettlementModeNotIn applies the NotIn predicate on the "settlement_mode" field. +func SettlementModeNotIn(vs ...productcatalog.SettlementMode) predicate.ChargeUsageBased { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldSettlementMode, v...)) +} + +// DiscountsIsNil applies the IsNil predicate on the "discounts" field. +func DiscountsIsNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIsNull(FieldDiscounts)) +} + +// DiscountsNotNil applies the NotNil predicate on the "discounts" field. +func DiscountsNotNil() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotNull(FieldDiscounts)) +} + +// FeatureKeyEQ applies the EQ predicate on the "feature_key" field. +func FeatureKeyEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEQ(FieldFeatureKey, v)) +} + +// FeatureKeyNEQ applies the NEQ predicate on the "feature_key" field. +func FeatureKeyNEQ(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNEQ(FieldFeatureKey, v)) +} + +// FeatureKeyIn applies the In predicate on the "feature_key" field. +func FeatureKeyIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyNotIn applies the NotIn predicate on the "feature_key" field. +func FeatureKeyNotIn(vs ...string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldNotIn(FieldFeatureKey, vs...)) +} + +// FeatureKeyGT applies the GT predicate on the "feature_key" field. +func FeatureKeyGT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGT(FieldFeatureKey, v)) +} + +// FeatureKeyGTE applies the GTE predicate on the "feature_key" field. +func FeatureKeyGTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldGTE(FieldFeatureKey, v)) +} + +// FeatureKeyLT applies the LT predicate on the "feature_key" field. +func FeatureKeyLT(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLT(FieldFeatureKey, v)) +} + +// FeatureKeyLTE applies the LTE predicate on the "feature_key" field. +func FeatureKeyLTE(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldLTE(FieldFeatureKey, v)) +} + +// FeatureKeyContains applies the Contains predicate on the "feature_key" field. +func FeatureKeyContains(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContains(FieldFeatureKey, v)) +} + +// FeatureKeyHasPrefix applies the HasPrefix predicate on the "feature_key" field. +func FeatureKeyHasPrefix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasPrefix(FieldFeatureKey, v)) +} + +// FeatureKeyHasSuffix applies the HasSuffix predicate on the "feature_key" field. +func FeatureKeyHasSuffix(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldHasSuffix(FieldFeatureKey, v)) +} + +// FeatureKeyEqualFold applies the EqualFold predicate on the "feature_key" field. +func FeatureKeyEqualFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldEqualFold(FieldFeatureKey, v)) +} + +// FeatureKeyContainsFold applies the ContainsFold predicate on the "feature_key" field. +func FeatureKeyContainsFold(v string) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.FieldContainsFold(FieldFeatureKey, v)) +} + +// HasCharge applies the HasEdge predicate on the "charge" edge. +func HasCharge() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, ChargeTable, ChargeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChargeWith applies the HasEdge predicate on the "charge" edge with a given conditions (other predicates). +func HasChargeWith(preds ...predicate.Charge) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newChargeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRuns applies the HasEdge predicate on the "runs" edge. +func HasRuns() predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RunsTable, RunsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRunsWith applies the HasEdge predicate on the "runs" edge with a given conditions (other predicates). +func HasRunsWith(preds ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(func(s *sql.Selector) { + step := newRunsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ChargeUsageBased) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBased) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBased) predicate.ChargeUsageBased { + return predicate.ChargeUsageBased(sql.NotPredicates(p)) +} diff --git a/openmeter/ent/db/chargeusagebased_create.go b/openmeter/ent/db/chargeusagebased_create.go new file mode 100644 index 0000000000..ec4146cb39 --- /dev/null +++ b/openmeter/ent/db/chargeusagebased_create.go @@ -0,0 +1,724 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// ChargeUsageBasedCreate is the builder for creating a ChargeUsageBased entity. +type ChargeUsageBasedCreate struct { + config + mutation *ChargeUsageBasedMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedCreate) SetNamespace(v string) *ChargeUsageBasedCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetInvoiceAt sets the "invoice_at" field. +func (_c *ChargeUsageBasedCreate) SetInvoiceAt(v time.Time) *ChargeUsageBasedCreate { + _c.mutation.SetInvoiceAt(v) + return _c +} + +// SetSettlementMode sets the "settlement_mode" field. +func (_c *ChargeUsageBasedCreate) SetSettlementMode(v productcatalog.SettlementMode) *ChargeUsageBasedCreate { + _c.mutation.SetSettlementMode(v) + return _c +} + +// SetDiscounts sets the "discounts" field. +func (_c *ChargeUsageBasedCreate) SetDiscounts(v *productcatalog.Discounts) *ChargeUsageBasedCreate { + _c.mutation.SetDiscounts(v) + return _c +} + +// SetFeatureKey sets the "feature_key" field. +func (_c *ChargeUsageBasedCreate) SetFeatureKey(v string) *ChargeUsageBasedCreate { + _c.mutation.SetFeatureKey(v) + return _c +} + +// SetPrice sets the "price" field. +func (_c *ChargeUsageBasedCreate) SetPrice(v *productcatalog.Price) *ChargeUsageBasedCreate { + _c.mutation.SetPrice(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedCreate) SetID(v string) *ChargeUsageBasedCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedCreate) SetNillableID(v *string) *ChargeUsageBasedCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetChargeID sets the "charge" edge to the Charge entity by ID. +func (_c *ChargeUsageBasedCreate) SetChargeID(id string) *ChargeUsageBasedCreate { + _c.mutation.SetChargeID(id) + return _c +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_c *ChargeUsageBasedCreate) SetCharge(v *Charge) *ChargeUsageBasedCreate { + return _c.SetChargeID(v.ID) +} + +// AddRunIDs adds the "runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (_c *ChargeUsageBasedCreate) AddRunIDs(ids ...string) *ChargeUsageBasedCreate { + _c.mutation.AddRunIDs(ids...) + return _c +} + +// AddRuns adds the "runs" edges to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedCreate) AddRuns(v ...*ChargeUsageBasedRuns) *ChargeUsageBasedCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddRunIDs(ids...) +} + +// Mutation returns the ChargeUsageBasedMutation object of the builder. +func (_c *ChargeUsageBasedCreate) Mutation() *ChargeUsageBasedMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBased in the database. +func (_c *ChargeUsageBasedCreate) Save(ctx context.Context) (*ChargeUsageBased, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedCreate) SaveX(ctx context.Context) *ChargeUsageBased { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ChargeUsageBasedCreate) defaults() { + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebased.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBased.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebased.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.InvoiceAt(); !ok { + return &ValidationError{Name: "invoice_at", err: errors.New(`db: missing required field "ChargeUsageBased.invoice_at"`)} + } + if _, ok := _c.mutation.SettlementMode(); !ok { + return &ValidationError{Name: "settlement_mode", err: errors.New(`db: missing required field "ChargeUsageBased.settlement_mode"`)} + } + if v, ok := _c.mutation.SettlementMode(); ok { + if err := chargeusagebased.SettlementModeValidator(v); err != nil { + return &ValidationError{Name: "settlement_mode", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.settlement_mode": %w`, err)} + } + } + if v, ok := _c.mutation.Discounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "discounts", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.discounts": %w`, err)} + } + } + if _, ok := _c.mutation.FeatureKey(); !ok { + return &ValidationError{Name: "feature_key", err: errors.New(`db: missing required field "ChargeUsageBased.feature_key"`)} + } + if v, ok := _c.mutation.FeatureKey(); ok { + if err := chargeusagebased.FeatureKeyValidator(v); err != nil { + return &ValidationError{Name: "feature_key", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.feature_key": %w`, err)} + } + } + if _, ok := _c.mutation.Price(); !ok { + return &ValidationError{Name: "price", err: errors.New(`db: missing required field "ChargeUsageBased.price"`)} + } + if v, ok := _c.mutation.Price(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "price", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.price": %w`, err)} + } + } + if len(_c.mutation.ChargeIDs()) == 0 { + return &ValidationError{Name: "charge", err: errors.New(`db: missing required edge "ChargeUsageBased.charge"`)} + } + return nil +} + +func (_c *ChargeUsageBasedCreate) sqlSave(ctx context.Context) (*ChargeUsageBased, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec, err := _c.createSpec() + if err != nil { + return nil, err + } + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected ChargeUsageBased.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedCreate) createSpec() (*ChargeUsageBased, *sqlgraph.CreateSpec, error) { + var ( + _node = &ChargeUsageBased{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebased.Table, sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebased.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.InvoiceAt(); ok { + _spec.SetField(chargeusagebased.FieldInvoiceAt, field.TypeTime, value) + _node.InvoiceAt = value + } + if value, ok := _c.mutation.SettlementMode(); ok { + _spec.SetField(chargeusagebased.FieldSettlementMode, field.TypeEnum, value) + _node.SettlementMode = value + } + if value, ok := _c.mutation.Discounts(); ok { + vv, err := chargeusagebased.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebased.FieldDiscounts, field.TypeString, vv) + _node.Discounts = value + } + if value, ok := _c.mutation.FeatureKey(); ok { + _spec.SetField(chargeusagebased.FieldFeatureKey, field.TypeString, value) + _node.FeatureKey = value + } + if value, ok := _c.mutation.Price(); ok { + vv, err := chargeusagebased.ValueScanner.Price.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(chargeusagebased.FieldPrice, field.TypeString, vv) + _node.Price = value + } + if nodes := _c.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebased.ChargeTable, + Columns: []string{chargeusagebased.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(charge.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.RunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec, nil +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBased.Create(). +// SetNamespace(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBased.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBased node. + ChargeUsageBasedUpsertOne struct { + create *ChargeUsageBasedCreate + } + + // ChargeUsageBasedUpsert is the "OnConflict" setter. + ChargeUsageBasedUpsert struct { + *sql.UpdateSet + } +) + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedUpsert) SetDiscounts(v *productcatalog.Discounts) *ChargeUsageBasedUpsert { + u.Set(chargeusagebased.FieldDiscounts, v) + return u +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsert) UpdateDiscounts() *ChargeUsageBasedUpsert { + u.SetExcluded(chargeusagebased.FieldDiscounts) + return u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeUsageBasedUpsert) ClearDiscounts() *ChargeUsageBasedUpsert { + u.SetNull(chargeusagebased.FieldDiscounts) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ChargeUsageBased.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebased.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedUpsertOne) UpdateNewValues() *ChargeUsageBasedUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(chargeusagebased.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebased.FieldNamespace) + } + if _, exists := u.create.mutation.InvoiceAt(); exists { + s.SetIgnore(chargeusagebased.FieldInvoiceAt) + } + if _, exists := u.create.mutation.SettlementMode(); exists { + s.SetIgnore(chargeusagebased.FieldSettlementMode) + } + if _, exists := u.create.mutation.FeatureKey(); exists { + s.SetIgnore(chargeusagebased.FieldFeatureKey) + } + if _, exists := u.create.mutation.Price(); exists { + s.SetIgnore(chargeusagebased.FieldPrice) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBased.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedUpsertOne) Ignore() *ChargeUsageBasedUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedUpsertOne) DoNothing() *ChargeUsageBasedUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedUpsertOne) Update(set func(*ChargeUsageBasedUpsert)) *ChargeUsageBasedUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedUpsert{UpdateSet: update}) + })) + return u +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedUpsertOne) SetDiscounts(v *productcatalog.Discounts) *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertOne) UpdateDiscounts() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateDiscounts() + }) +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeUsageBasedUpsertOne) ClearDiscounts() *ChargeUsageBasedUpsertOne { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearDiscounts() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ChargeUsageBasedUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: ChargeUsageBasedUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ChargeUsageBasedUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedCreateBulk is the builder for creating many ChargeUsageBased entities in bulk. +type ChargeUsageBasedCreateBulk struct { + config + err error + builders []*ChargeUsageBasedCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBased entities in the database. +func (_c *ChargeUsageBasedCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBased, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBased, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ChargeUsageBasedMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i], err = builder.createSpec() + if err != nil { + return nil, err + } + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ChargeUsageBasedCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBased { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBased.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBased.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBased nodes. +type ChargeUsageBasedUpsertBulk struct { + create *ChargeUsageBasedCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBased.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebased.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedUpsertBulk) UpdateNewValues() *ChargeUsageBasedUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(chargeusagebased.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebased.FieldNamespace) + } + if _, exists := b.mutation.InvoiceAt(); exists { + s.SetIgnore(chargeusagebased.FieldInvoiceAt) + } + if _, exists := b.mutation.SettlementMode(); exists { + s.SetIgnore(chargeusagebased.FieldSettlementMode) + } + if _, exists := b.mutation.FeatureKey(); exists { + s.SetIgnore(chargeusagebased.FieldFeatureKey) + } + if _, exists := b.mutation.Price(); exists { + s.SetIgnore(chargeusagebased.FieldPrice) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBased.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedUpsertBulk) Ignore() *ChargeUsageBasedUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedUpsertBulk) DoNothing() *ChargeUsageBasedUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedUpsertBulk) Update(set func(*ChargeUsageBasedUpsert)) *ChargeUsageBasedUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedUpsert{UpdateSet: update}) + })) + return u +} + +// SetDiscounts sets the "discounts" field. +func (u *ChargeUsageBasedUpsertBulk) SetDiscounts(v *productcatalog.Discounts) *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.SetDiscounts(v) + }) +} + +// UpdateDiscounts sets the "discounts" field to the value that was provided on create. +func (u *ChargeUsageBasedUpsertBulk) UpdateDiscounts() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.UpdateDiscounts() + }) +} + +// ClearDiscounts clears the value of the "discounts" field. +func (u *ChargeUsageBasedUpsertBulk) ClearDiscounts() *ChargeUsageBasedUpsertBulk { + return u.Update(func(s *ChargeUsageBasedUpsert) { + s.ClearDiscounts() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ChargeUsageBasedCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebased_delete.go b/openmeter/ent/db/chargeusagebased_delete.go new file mode 100644 index 0000000000..41b4836f88 --- /dev/null +++ b/openmeter/ent/db/chargeusagebased_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedDelete is the builder for deleting a ChargeUsageBased entity. +type ChargeUsageBasedDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedMutation +} + +// Where appends a list predicates to the ChargeUsageBasedDelete builder. +func (_d *ChargeUsageBasedDelete) Where(ps ...predicate.ChargeUsageBased) *ChargeUsageBasedDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebased.Table, sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ChargeUsageBasedDeleteOne is the builder for deleting a single ChargeUsageBased entity. +type ChargeUsageBasedDeleteOne struct { + _d *ChargeUsageBasedDelete +} + +// Where appends a list predicates to the ChargeUsageBasedDelete builder. +func (_d *ChargeUsageBasedDeleteOne) Where(ps ...predicate.ChargeUsageBased) *ChargeUsageBasedDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebased.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebased_query.go b/openmeter/ent/db/chargeusagebased_query.go new file mode 100644 index 0000000000..d3ea7b533c --- /dev/null +++ b/openmeter/ent/db/chargeusagebased_query.go @@ -0,0 +1,715 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedQuery is the builder for querying ChargeUsageBased entities. +type ChargeUsageBasedQuery struct { + config + ctx *QueryContext + order []chargeusagebased.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBased + withCharge *ChargeQuery + withRuns *ChargeUsageBasedRunsQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ChargeUsageBasedQuery builder. +func (_q *ChargeUsageBasedQuery) Where(ps ...predicate.ChargeUsageBased) *ChargeUsageBasedQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedQuery) Limit(limit int) *ChargeUsageBasedQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedQuery) Offset(offset int) *ChargeUsageBasedQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ChargeUsageBasedQuery) Unique(unique bool) *ChargeUsageBasedQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedQuery) Order(o ...chargeusagebased.OrderOption) *ChargeUsageBasedQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryCharge chains the current query on the "charge" edge. +func (_q *ChargeUsageBasedQuery) QueryCharge() *ChargeQuery { + query := (&ChargeClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebased.Table, chargeusagebased.FieldID, selector), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebased.ChargeTable, chargeusagebased.ChargeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRuns chains the current query on the "runs" edge. +func (_q *ChargeUsageBasedQuery) QueryRuns() *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebased.Table, chargeusagebased.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebased.RunsTable, chargeusagebased.RunsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBased entity from the query. +// Returns a *NotFoundError when no ChargeUsageBased was found. +func (_q *ChargeUsageBasedQuery) First(ctx context.Context) (*ChargeUsageBased, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{chargeusagebased.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) FirstX(ctx context.Context) *ChargeUsageBased { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBased ID from the query. +// Returns a *NotFoundError when no ChargeUsageBased ID was found. +func (_q *ChargeUsageBasedQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{chargeusagebased.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBased entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBased entity is found. +// Returns a *NotFoundError when no ChargeUsageBased entities are found. +func (_q *ChargeUsageBasedQuery) Only(ctx context.Context) (*ChargeUsageBased, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{chargeusagebased.Label} + default: + return nil, &NotSingularError{chargeusagebased.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) OnlyX(ctx context.Context) *ChargeUsageBased { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBased ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBased ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{chargeusagebased.Label} + default: + err = &NotSingularError{chargeusagebased.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ChargeUsageBaseds. +func (_q *ChargeUsageBasedQuery) All(ctx context.Context) ([]*ChargeUsageBased, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBased, *ChargeUsageBasedQuery]() + return withInterceptors[[]*ChargeUsageBased](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) AllX(ctx context.Context) []*ChargeUsageBased { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBased IDs. +func (_q *ChargeUsageBasedQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(chargeusagebased.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ChargeUsageBasedQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ChargeUsageBasedQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ChargeUsageBasedQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ChargeUsageBasedQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ChargeUsageBasedQuery) Clone() *ChargeUsageBasedQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebased.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBased{}, _q.predicates...), + withCharge: _q.withCharge.Clone(), + withRuns: _q.withRuns.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithCharge tells the query-builder to eager-load the nodes that are connected to +// the "charge" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithCharge(opts ...func(*ChargeQuery)) *ChargeUsageBasedQuery { + query := (&ChargeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCharge = query + return _q +} + +// WithRuns tells the query-builder to eager-load the nodes that are connected to +// the "runs" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedQuery) WithRuns(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRuns = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Namespace string `json:"namespace,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBased.Query(). +// GroupBy(chargeusagebased.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebased.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Namespace string `json:"namespace,omitempty"` +// } +// +// client.ChargeUsageBased.Query(). +// Select(chargeusagebased.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedQuery) Select(fields ...string) *ChargeUsageBasedSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedSelect{ChargeUsageBasedQuery: _q} + sbuild.label = chargeusagebased.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedSelect configured with the given aggregations. +func (_q *ChargeUsageBasedQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !chargeusagebased.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ChargeUsageBasedQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBased, error) { + var ( + nodes = []*ChargeUsageBased{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withCharge != nil, + _q.withRuns != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBased).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBased{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withCharge; query != nil { + if err := _q.loadCharge(ctx, query, nodes, nil, + func(n *ChargeUsageBased, e *Charge) { n.Edges.Charge = e }); err != nil { + return nil, err + } + } + if query := _q.withRuns; query != nil { + if err := _q.loadRuns(ctx, query, nodes, + func(n *ChargeUsageBased) { n.Edges.Runs = []*ChargeUsageBasedRuns{} }, + func(n *ChargeUsageBased, e *ChargeUsageBasedRuns) { n.Edges.Runs = append(n.Edges.Runs, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedQuery) loadCharge(ctx context.Context, query *ChargeQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *Charge)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBased) + for i := range nodes { + fk := nodes[i].ID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(charge.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedQuery) loadRuns(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBased, init func(*ChargeUsageBased), assign func(*ChargeUsageBased, *ChargeUsageBasedRuns)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeUsageBased) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(chargeusagebasedruns.FieldChargeID) + } + query.Where(predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebased.RunsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ChargeID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "charge_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *ChargeUsageBasedQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ChargeUsageBasedQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebased.Table, chargeusagebased.Columns, sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebased.FieldID) + for i := range fields { + if fields[i] != chargeusagebased.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ChargeUsageBasedQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebased.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebased.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *ChargeUsageBasedQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *ChargeUsageBasedQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedGroupBy is the group-by builder for ChargeUsageBased entities. +type ChargeUsageBasedGroupBy struct { + selector + build *ChargeUsageBasedQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedQuery, *ChargeUsageBasedGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ChargeUsageBasedSelect is the builder for selecting fields of ChargeUsageBased entities. +type ChargeUsageBasedSelect struct { + *ChargeUsageBasedQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedQuery, *ChargeUsageBasedSelect](ctx, _s.ChargeUsageBasedQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/openmeter/ent/db/chargeusagebased_update.go b/openmeter/ent/db/chargeusagebased_update.go new file mode 100644 index 0000000000..31c59073af --- /dev/null +++ b/openmeter/ent/db/chargeusagebased_update.go @@ -0,0 +1,508 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/charge" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/openmeter/productcatalog" +) + +// ChargeUsageBasedUpdate is the builder for updating ChargeUsageBased entities. +type ChargeUsageBasedUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedMutation +} + +// Where appends a list predicates to the ChargeUsageBasedUpdate builder. +func (_u *ChargeUsageBasedUpdate) Where(ps ...predicate.ChargeUsageBased) *ChargeUsageBasedUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeUsageBasedUpdate) SetDiscounts(v *productcatalog.Discounts) *ChargeUsageBasedUpdate { + _u.mutation.SetDiscounts(v) + return _u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (_u *ChargeUsageBasedUpdate) ClearDiscounts() *ChargeUsageBasedUpdate { + _u.mutation.ClearDiscounts() + return _u +} + +// SetChargeID sets the "charge" edge to the Charge entity by ID. +func (_u *ChargeUsageBasedUpdate) SetChargeID(id string) *ChargeUsageBasedUpdate { + _u.mutation.SetChargeID(id) + return _u +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_u *ChargeUsageBasedUpdate) SetCharge(v *Charge) *ChargeUsageBasedUpdate { + return _u.SetChargeID(v.ID) +} + +// AddRunIDs adds the "runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (_u *ChargeUsageBasedUpdate) AddRunIDs(ids ...string) *ChargeUsageBasedUpdate { + _u.mutation.AddRunIDs(ids...) + return _u +} + +// AddRuns adds the "runs" edges to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdate) AddRuns(v ...*ChargeUsageBasedRuns) *ChargeUsageBasedUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRunIDs(ids...) +} + +// Mutation returns the ChargeUsageBasedMutation object of the builder. +func (_u *ChargeUsageBasedUpdate) Mutation() *ChargeUsageBasedMutation { + return _u.mutation +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (_u *ChargeUsageBasedUpdate) ClearCharge() *ChargeUsageBasedUpdate { + _u.mutation.ClearCharge() + return _u +} + +// ClearRuns clears all "runs" edges to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdate) ClearRuns() *ChargeUsageBasedUpdate { + _u.mutation.ClearRuns() + return _u +} + +// RemoveRunIDs removes the "runs" edge to ChargeUsageBasedRuns entities by IDs. +func (_u *ChargeUsageBasedUpdate) RemoveRunIDs(ids ...string) *ChargeUsageBasedUpdate { + _u.mutation.RemoveRunIDs(ids...) + return _u +} + +// RemoveRuns removes "runs" edges to ChargeUsageBasedRuns entities. +func (_u *ChargeUsageBasedUpdate) RemoveRuns(v ...*ChargeUsageBasedRuns) *ChargeUsageBasedUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRunIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedUpdate) check() error { + if v, ok := _u.mutation.Discounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "discounts", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.discounts": %w`, err)} + } + } + if _u.mutation.ChargeCleared() && len(_u.mutation.ChargeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.charge"`) + } + return nil +} + +func (_u *ChargeUsageBasedUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebased.Table, chargeusagebased.Columns, sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeusagebased.ValueScanner.Discounts.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(chargeusagebased.FieldDiscounts, field.TypeString, vv) + } + if _u.mutation.DiscountsCleared() { + _spec.ClearField(chargeusagebased.FieldDiscounts, field.TypeString) + } + if _u.mutation.ChargeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebased.ChargeTable, + Columns: []string{chargeusagebased.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(charge.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebased.ChargeTable, + Columns: []string{chargeusagebased.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(charge.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.RunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRunsIDs(); len(nodes) > 0 && !_u.mutation.RunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebased.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedUpdateOne is the builder for updating a single ChargeUsageBased entity. +type ChargeUsageBasedUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedMutation +} + +// SetDiscounts sets the "discounts" field. +func (_u *ChargeUsageBasedUpdateOne) SetDiscounts(v *productcatalog.Discounts) *ChargeUsageBasedUpdateOne { + _u.mutation.SetDiscounts(v) + return _u +} + +// ClearDiscounts clears the value of the "discounts" field. +func (_u *ChargeUsageBasedUpdateOne) ClearDiscounts() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearDiscounts() + return _u +} + +// SetChargeID sets the "charge" edge to the Charge entity by ID. +func (_u *ChargeUsageBasedUpdateOne) SetChargeID(id string) *ChargeUsageBasedUpdateOne { + _u.mutation.SetChargeID(id) + return _u +} + +// SetCharge sets the "charge" edge to the Charge entity. +func (_u *ChargeUsageBasedUpdateOne) SetCharge(v *Charge) *ChargeUsageBasedUpdateOne { + return _u.SetChargeID(v.ID) +} + +// AddRunIDs adds the "runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (_u *ChargeUsageBasedUpdateOne) AddRunIDs(ids ...string) *ChargeUsageBasedUpdateOne { + _u.mutation.AddRunIDs(ids...) + return _u +} + +// AddRuns adds the "runs" edges to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdateOne) AddRuns(v ...*ChargeUsageBasedRuns) *ChargeUsageBasedUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRunIDs(ids...) +} + +// Mutation returns the ChargeUsageBasedMutation object of the builder. +func (_u *ChargeUsageBasedUpdateOne) Mutation() *ChargeUsageBasedMutation { + return _u.mutation +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (_u *ChargeUsageBasedUpdateOne) ClearCharge() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearCharge() + return _u +} + +// ClearRuns clears all "runs" edges to the ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedUpdateOne) ClearRuns() *ChargeUsageBasedUpdateOne { + _u.mutation.ClearRuns() + return _u +} + +// RemoveRunIDs removes the "runs" edge to ChargeUsageBasedRuns entities by IDs. +func (_u *ChargeUsageBasedUpdateOne) RemoveRunIDs(ids ...string) *ChargeUsageBasedUpdateOne { + _u.mutation.RemoveRunIDs(ids...) + return _u +} + +// RemoveRuns removes "runs" edges to ChargeUsageBasedRuns entities. +func (_u *ChargeUsageBasedUpdateOne) RemoveRuns(v ...*ChargeUsageBasedRuns) *ChargeUsageBasedUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRunIDs(ids...) +} + +// Where appends a list predicates to the ChargeUsageBasedUpdate builder. +func (_u *ChargeUsageBasedUpdateOne) Where(ps ...predicate.ChargeUsageBased) *ChargeUsageBasedUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ChargeUsageBasedUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBased entity. +func (_u *ChargeUsageBasedUpdateOne) Save(ctx context.Context) (*ChargeUsageBased, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedUpdateOne) SaveX(ctx context.Context) *ChargeUsageBased { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedUpdateOne) check() error { + if v, ok := _u.mutation.Discounts(); ok { + if err := v.Validate(); err != nil { + return &ValidationError{Name: "discounts", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBased.discounts": %w`, err)} + } + } + if _u.mutation.ChargeCleared() && len(_u.mutation.ChargeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBased.charge"`) + } + return nil +} + +func (_u *ChargeUsageBasedUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBased, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebased.Table, chargeusagebased.Columns, sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBased.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebased.FieldID) + for _, f := range fields { + if !chargeusagebased.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebased.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Discounts(); ok { + vv, err := chargeusagebased.ValueScanner.Discounts.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(chargeusagebased.FieldDiscounts, field.TypeString, vv) + } + if _u.mutation.DiscountsCleared() { + _spec.ClearField(chargeusagebased.FieldDiscounts, field.TypeString) + } + if _u.mutation.ChargeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebased.ChargeTable, + Columns: []string{chargeusagebased.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(charge.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChargeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebased.ChargeTable, + Columns: []string{chargeusagebased.ChargeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(charge.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.RunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRunsIDs(); len(nodes) > 0 && !_u.mutation.RunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebased.RunsTable, + Columns: []string{chargeusagebased.RunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeUsageBased{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebased.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations.go b/openmeter/ent/db/chargeusagebasedruncreditallocations.go new file mode 100644 index 0000000000..313d396921 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations.go @@ -0,0 +1,258 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunCreditAllocations is the model entity for the ChargeUsageBasedRunCreditAllocations schema. +type ChargeUsageBasedRunCreditAllocations struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // LineID holds the value of the "line_id" field. + LineID *string `json:"line_id,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // ServicePeriodFrom holds the value of the "service_period_from" field. + ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` + // ServicePeriodTo holds the value of the "service_period_to" field. + ServicePeriodTo time.Time `json:"service_period_to,omitempty"` + // LedgerTransactionGroupID holds the value of the "ledger_transaction_group_id" field. + LedgerTransactionGroupID string `json:"ledger_transaction_group_id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // RunID holds the value of the "run_id" field. + RunID string `json:"run_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedRunCreditAllocationsQuery when eager-loading is set. + Edges ChargeUsageBasedRunCreditAllocationsEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedRunCreditAllocationsEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedRunCreditAllocationsEdges struct { + // Run holds the value of the run edge. + Run *ChargeUsageBasedRuns `json:"run,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// RunOrErr returns the Run value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunCreditAllocationsEdges) RunOrErr() (*ChargeUsageBasedRuns, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeusagebasedruns.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBasedRunCreditAllocations) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebasedruncreditallocations.FieldAnnotations: + values[i] = new([]byte) + case chargeusagebasedruncreditallocations.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case chargeusagebasedruncreditallocations.FieldID, chargeusagebasedruncreditallocations.FieldLineID, chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID, chargeusagebasedruncreditallocations.FieldNamespace, chargeusagebasedruncreditallocations.FieldRunID: + values[i] = new(sql.NullString) + case chargeusagebasedruncreditallocations.FieldServicePeriodFrom, chargeusagebasedruncreditallocations.FieldServicePeriodTo, chargeusagebasedruncreditallocations.FieldCreatedAt, chargeusagebasedruncreditallocations.FieldUpdatedAt, chargeusagebasedruncreditallocations.FieldDeletedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeUsageBasedRunCreditAllocations fields. +func (_m *ChargeUsageBasedRunCreditAllocations) 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) + } + for i := range columns { + switch columns[i] { + case chargeusagebasedruncreditallocations.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case chargeusagebasedruncreditallocations.FieldLineID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field line_id", values[i]) + } else if value.Valid { + _m.LineID = new(string) + *_m.LineID = value.String + } + case chargeusagebasedruncreditallocations.FieldAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount", values[i]) + } else if value != nil { + _m.Amount = *value + } + case chargeusagebasedruncreditallocations.FieldServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_from", values[i]) + } else if value.Valid { + _m.ServicePeriodFrom = value.Time + } + case chargeusagebasedruncreditallocations.FieldServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_to", values[i]) + } else if value.Valid { + _m.ServicePeriodTo = value.Time + } + case chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ledger_transaction_group_id", values[i]) + } else if value.Valid { + _m.LedgerTransactionGroupID = value.String + } + case chargeusagebasedruncreditallocations.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + _m.Namespace = value.String + } + case chargeusagebasedruncreditallocations.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case chargeusagebasedruncreditallocations.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case chargeusagebasedruncreditallocations.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = new(time.Time) + *_m.DeletedAt = value.Time + } + case chargeusagebasedruncreditallocations.FieldAnnotations: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field annotations", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Annotations); err != nil { + return fmt.Errorf("unmarshal field annotations: %w", err) + } + } + case chargeusagebasedruncreditallocations.FieldRunID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field run_id", values[i]) + } else if value.Valid { + _m.RunID = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeUsageBasedRunCreditAllocations. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBasedRunCreditAllocations) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRun queries the "run" edge of the ChargeUsageBasedRunCreditAllocations entity. +func (_m *ChargeUsageBasedRunCreditAllocations) QueryRun() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedRunCreditAllocationsClient(_m.config).QueryRun(_m) +} + +// Update returns a builder for updating this ChargeUsageBasedRunCreditAllocations. +// Note that you need to call ChargeUsageBasedRunCreditAllocations.Unwrap() before calling this method if this ChargeUsageBasedRunCreditAllocations +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBasedRunCreditAllocations) Update() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + return NewChargeUsageBasedRunCreditAllocationsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBasedRunCreditAllocations 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 (_m *ChargeUsageBasedRunCreditAllocations) Unwrap() *ChargeUsageBasedRunCreditAllocations { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBasedRunCreditAllocations is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBasedRunCreditAllocations) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBasedRunCreditAllocations(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + if v := _m.LineID; v != nil { + builder.WriteString("line_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("service_period_from=") + builder.WriteString(_m.ServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_to=") + builder.WriteString(_m.ServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("ledger_transaction_group_id=") + builder.WriteString(_m.LedgerTransactionGroupID) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("run_id=") + builder.WriteString(_m.RunID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunCreditAllocationsSlice is a parsable slice of ChargeUsageBasedRunCreditAllocations. +type ChargeUsageBasedRunCreditAllocationsSlice []*ChargeUsageBasedRunCreditAllocations diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations/chargeusagebasedruncreditallocations.go b/openmeter/ent/db/chargeusagebasedruncreditallocations/chargeusagebasedruncreditallocations.go new file mode 100644 index 0000000000..ef6e6cc93d --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations/chargeusagebasedruncreditallocations.go @@ -0,0 +1,165 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruncreditallocations + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the chargeusagebasedruncreditallocations type in the database. + Label = "charge_usage_based_run_credit_allocations" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldServicePeriodFrom holds the string denoting the service_period_from field in the database. + FieldServicePeriodFrom = "service_period_from" + // FieldServicePeriodTo holds the string denoting the service_period_to field in the database. + FieldServicePeriodTo = "service_period_to" + // FieldLedgerTransactionGroupID holds the string denoting the ledger_transaction_group_id field in the database. + FieldLedgerTransactionGroupID = "ledger_transaction_group_id" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldRunID holds the string denoting the run_id field in the database. + FieldRunID = "run_id" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // Table holds the table name of the chargeusagebasedruncreditallocations in the database. + Table = "charge_usage_based_run_credit_allocations" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_usage_based_run_credit_allocations" + // RunInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + RunInverseTable = "charge_usage_based_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" +) + +// Columns holds all SQL columns for chargeusagebasedruncreditallocations fields. +var Columns = []string{ + FieldID, + FieldLineID, + FieldAmount, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldLedgerTransactionGroupID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldRunID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // LineIDValidator is a validator for the "line_id" field. It is called by the builders before save. + LineIDValidator func(string) error + // LedgerTransactionGroupIDValidator is a validator for the "ledger_transaction_group_id" field. It is called by the builders before save. + LedgerTransactionGroupIDValidator func(string) error + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the ChargeUsageBasedRunCreditAllocations 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() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByServicePeriodFrom orders the results by the service_period_from field. +func ByServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodFrom, opts...).ToFunc() +} + +// ByServicePeriodTo orders the results by the service_period_to field. +func ByServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodTo, opts...).ToFunc() +} + +// ByLedgerTransactionGroupID orders the results by the ledger_transaction_group_id field. +func ByLedgerTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLedgerTransactionGroupID, opts...).ToFunc() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByRunID orders the results by the run_id field. +func ByRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRunID, opts...).ToFunc() +} + +// ByRunField orders the results by run field. +func ByRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRunStep(), sql.OrderByField(field, opts...)) + } +} +func newRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RunTable, RunColumn), + ) +} diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations/where.go b/openmeter/ent/db/chargeusagebasedruncreditallocations/where.go new file mode 100644 index 0000000000..1918f13282 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations/where.go @@ -0,0 +1,685 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruncreditallocations + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContainsFold(FieldID, id)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldLineID, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldAmount, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodTo applies equality check predicate on the "service_period_to" field. It's identical to ServicePeriodToEQ. +func ServicePeriodTo(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// LedgerTransactionGroupID applies equality check predicate on the "ledger_transaction_group_id" field. It's identical to LedgerTransactionGroupIDEQ. +func LedgerTransactionGroupID(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldNamespace, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldDeletedAt, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldRunID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDIsNil applies the IsNil predicate on the "line_id" field. +func LineIDIsNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIsNull(FieldLineID)) +} + +// LineIDNotNil applies the NotNil predicate on the "line_id" field. +func LineIDNotNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotNull(FieldLineID)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContainsFold(FieldLineID, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldAmount, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// LedgerTransactionGroupIDEQ applies the EQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDNEQ applies the NEQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDIn applies the In predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDNotIn applies the NotIn predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNotIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDGT applies the GT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDGTE applies the GTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLT applies the LT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLTE applies the LTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContains applies the Contains predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContains(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContains(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasPrefix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasPrefix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasSuffix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasSuffix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDEqualFold applies the EqualFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEqualFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEqualFold(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContainsFold applies the ContainsFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContainsFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContainsFold(FieldLedgerTransactionGroupID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotNull(FieldAnnotations)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.FieldContainsFold(FieldRunID, v)) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RunTable, RunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRunWith applies the HasEdge predicate on the "run" edge with a given conditions (other predicates). +func HasRunWith(preds ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + step := newRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ChargeUsageBasedRunCreditAllocations) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBasedRunCreditAllocations) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBasedRunCreditAllocations) predicate.ChargeUsageBasedRunCreditAllocations { + return predicate.ChargeUsageBasedRunCreditAllocations(sql.NotPredicates(p)) +} diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations_create.go b/openmeter/ent/db/chargeusagebasedruncreditallocations_create.go new file mode 100644 index 0000000000..c28484e150 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations_create.go @@ -0,0 +1,1032 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunCreditAllocationsCreate is the builder for creating a ChargeUsageBasedRunCreditAllocations entity. +type ChargeUsageBasedRunCreditAllocationsCreate struct { + config + mutation *ChargeUsageBasedRunCreditAllocationsMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetLineID(v string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableLineID(v *string) *ChargeUsageBasedRunCreditAllocationsCreate { + if v != nil { + _c.SetLineID(*v) + } + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetLedgerTransactionGroupID(v) + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNamespace(v string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetCreatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableCreatedAt(v *time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableUpdatedAt(v *time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunCreditAllocationsCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetRunID(v string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetID(v string) *ChargeUsageBasedRunCreditAllocationsCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetNillableID(v *string) *ChargeUsageBasedRunCreditAllocationsCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRun sets the "run" edge to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SetRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunCreditAllocationsCreate { + return _c.SetRunID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunCreditAllocationsMutation object of the builder. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) Mutation() *ChargeUsageBasedRunCreditAllocationsMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBasedRunCreditAllocations in the database. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) Save(ctx context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) SaveX(ctx context.Context) *ChargeUsageBasedRunCreditAllocations { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeusagebasedruncreditallocations.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruncreditallocations.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebasedruncreditallocations.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) check() error { + if v, ok := _c.mutation.LineID(); ok { + if err := chargeusagebasedruncreditallocations.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.line_id": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.amount"`)} + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.service_period_to"`)} + } + if _, ok := _c.mutation.LedgerTransactionGroupID(); !ok { + return &ValidationError{Name: "ledger_transaction_group_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.ledger_transaction_group_id"`)} + } + if v, ok := _c.mutation.LedgerTransactionGroupID(); ok { + if err := chargeusagebasedruncreditallocations.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.ledger_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebasedruncreditallocations.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.updated_at"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunCreditAllocations.run_id"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeUsageBasedRunCreditAllocations.run"`)} + } + return nil +} + +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) sqlSave(ctx context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected ChargeUsageBasedRunCreditAllocations.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) createSpec() (*ChargeUsageBasedRunCreditAllocations, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeUsageBasedRunCreditAllocations{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebasedruncreditallocations.Table, sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldLineID, field.TypeString, value) + _node.LineID = &value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID, field.TypeString, value) + _node.LedgerTransactionGroupID = value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedruncreditallocations.RunTable, + Columns: []string{chargeusagebasedruncreditallocations.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RunID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// SetLineID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunCreditAllocationsUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedRunCreditAllocationsUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunCreditAllocationsCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunCreditAllocationsUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedRunCreditAllocationsUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBasedRunCreditAllocations node. + ChargeUsageBasedRunCreditAllocationsUpsertOne struct { + create *ChargeUsageBasedRunCreditAllocationsCreate + } + + // ChargeUsageBasedRunCreditAllocationsUpsert is the "OnConflict" setter. + ChargeUsageBasedRunCreditAllocationsUpsert struct { + *sql.UpdateSet + } +) + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetLineID(v string) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateLineID() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldLineID) + return u +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) ClearLineID() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetNull(chargeusagebasedruncreditallocations.FieldLineID) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateAmount() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldAmount) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateServicePeriodFrom() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateServicePeriodTo() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldServicePeriodTo) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateUpdatedAt() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetDeletedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) ClearDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetNull(chargeusagebasedruncreditallocations.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpsert { + u.Set(chargeusagebasedruncreditallocations.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) UpdateAnnotations() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetExcluded(chargeusagebasedruncreditallocations.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsert) ClearAnnotations() *ChargeUsageBasedRunCreditAllocationsUpsert { + u.SetNull(chargeusagebasedruncreditallocations.FieldAnnotations) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedruncreditallocations.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateNewValues() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldID) + } + if _, exists := u.create.mutation.LedgerTransactionGroupID(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) Ignore() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) DoNothing() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunCreditAllocationsCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) Update(set func(*ChargeUsageBasedRunCreditAllocationsUpsert)) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunCreditAllocationsUpsert{UpdateSet: update}) + })) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetLineID(v string) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateLineID() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) ClearLineID() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearLineID() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateAmount() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateAmount() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateServicePeriodFrom() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateServicePeriodTo() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateUpdatedAt() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) ClearDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) UpdateAnnotations() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) ClearAnnotations() *ChargeUsageBasedRunCreditAllocationsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunCreditAllocationsCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: ChargeUsageBasedRunCreditAllocationsUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedRunCreditAllocationsUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedRunCreditAllocationsCreateBulk is the builder for creating many ChargeUsageBasedRunCreditAllocations entities in bulk. +type ChargeUsageBasedRunCreditAllocationsCreateBulk struct { + config + err error + builders []*ChargeUsageBasedRunCreditAllocationsCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBasedRunCreditAllocations entities in the database. +func (_c *ChargeUsageBasedRunCreditAllocationsCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBasedRunCreditAllocations, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBasedRunCreditAllocations, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ChargeUsageBasedRunCreditAllocationsMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ChargeUsageBasedRunCreditAllocationsCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBasedRunCreditAllocations { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunCreditAllocationsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunCreditAllocationsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRunCreditAllocations.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunCreditAllocationsUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunCreditAllocationsCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedRunCreditAllocationsUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunCreditAllocationsCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunCreditAllocationsUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedRunCreditAllocationsUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBasedRunCreditAllocations nodes. +type ChargeUsageBasedRunCreditAllocationsUpsertBulk struct { + create *ChargeUsageBasedRunCreditAllocationsCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedruncreditallocations.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateNewValues() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldID) + } + if _, exists := b.mutation.LedgerTransactionGroupID(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeusagebasedruncreditallocations.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunCreditAllocations.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) Ignore() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) DoNothing() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunCreditAllocationsCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) Update(set func(*ChargeUsageBasedRunCreditAllocationsUpsert)) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunCreditAllocationsUpsert{UpdateSet: update}) + })) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetLineID(v string) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateLineID() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) ClearLineID() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearLineID() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateAmount() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateAmount() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateServicePeriodFrom() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateServicePeriodTo() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateUpdatedAt() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetDeletedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) ClearDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) UpdateAnnotations() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) ClearAnnotations() *ChargeUsageBasedRunCreditAllocationsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunCreditAllocationsUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ChargeUsageBasedRunCreditAllocationsCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunCreditAllocationsCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunCreditAllocationsUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations_delete.go b/openmeter/ent/db/chargeusagebasedruncreditallocations_delete.go new file mode 100644 index 0000000000..fd9166d171 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunCreditAllocationsDelete is the builder for deleting a ChargeUsageBasedRunCreditAllocations entity. +type ChargeUsageBasedRunCreditAllocationsDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunCreditAllocationsMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunCreditAllocationsDelete builder. +func (_d *ChargeUsageBasedRunCreditAllocationsDelete) Where(ps ...predicate.ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedRunCreditAllocationsDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunCreditAllocationsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedRunCreditAllocationsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebasedruncreditallocations.Table, sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ChargeUsageBasedRunCreditAllocationsDeleteOne is the builder for deleting a single ChargeUsageBasedRunCreditAllocations entity. +type ChargeUsageBasedRunCreditAllocationsDeleteOne struct { + _d *ChargeUsageBasedRunCreditAllocationsDelete +} + +// Where appends a list predicates to the ChargeUsageBasedRunCreditAllocationsDelete builder. +func (_d *ChargeUsageBasedRunCreditAllocationsDeleteOne) Where(ps ...predicate.ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedRunCreditAllocationsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebasedruncreditallocations.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunCreditAllocationsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations_query.go b/openmeter/ent/db/chargeusagebasedruncreditallocations_query.go new file mode 100644 index 0000000000..785fc25df0 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations_query.go @@ -0,0 +1,643 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunCreditAllocationsQuery is the builder for querying ChargeUsageBasedRunCreditAllocations entities. +type ChargeUsageBasedRunCreditAllocationsQuery struct { + config + ctx *QueryContext + order []chargeusagebasedruncreditallocations.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBasedRunCreditAllocations + withRun *ChargeUsageBasedRunsQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ChargeUsageBasedRunCreditAllocationsQuery builder. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Where(ps ...predicate.ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Limit(limit int) *ChargeUsageBasedRunCreditAllocationsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Offset(offset int) *ChargeUsageBasedRunCreditAllocationsQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ChargeUsageBasedRunCreditAllocationsQuery) Unique(unique bool) *ChargeUsageBasedRunCreditAllocationsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Order(o ...chargeusagebasedruncreditallocations.OrderOption) *ChargeUsageBasedRunCreditAllocationsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) QueryRun() *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruncreditallocations.RunTable, chargeusagebasedruncreditallocations.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBasedRunCreditAllocations entity from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunCreditAllocations was found. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) First(ctx context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{chargeusagebasedruncreditallocations.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) FirstX(ctx context.Context) *ChargeUsageBasedRunCreditAllocations { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBasedRunCreditAllocations ID from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunCreditAllocations ID was found. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{chargeusagebasedruncreditallocations.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBasedRunCreditAllocations entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunCreditAllocations entity is found. +// Returns a *NotFoundError when no ChargeUsageBasedRunCreditAllocations entities are found. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Only(ctx context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{chargeusagebasedruncreditallocations.Label} + default: + return nil, &NotSingularError{chargeusagebasedruncreditallocations.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) OnlyX(ctx context.Context) *ChargeUsageBasedRunCreditAllocations { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBasedRunCreditAllocations ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunCreditAllocations ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{chargeusagebasedruncreditallocations.Label} + default: + err = &NotSingularError{chargeusagebasedruncreditallocations.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ChargeUsageBasedRunCreditAllocationsSlice. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) All(ctx context.Context) ([]*ChargeUsageBasedRunCreditAllocations, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBasedRunCreditAllocations, *ChargeUsageBasedRunCreditAllocationsQuery]() + return withInterceptors[[]*ChargeUsageBasedRunCreditAllocations](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) AllX(ctx context.Context) []*ChargeUsageBasedRunCreditAllocations { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBasedRunCreditAllocations IDs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(chargeusagebasedruncreditallocations.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ChargeUsageBasedRunCreditAllocationsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedRunCreditAllocationsQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Clone() *ChargeUsageBasedRunCreditAllocationsQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedRunCreditAllocationsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebasedruncreditallocations.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBasedRunCreditAllocations{}, _q.predicates...), + withRun: _q.withRun.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithRun tells the query-builder to eager-load the nodes that are connected to +// the "run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) WithRun(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRun = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// LineID string `json:"line_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBasedRunCreditAllocations.Query(). +// GroupBy(chargeusagebasedruncreditallocations.FieldLineID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedRunCreditAllocationsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedRunCreditAllocationsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebasedruncreditallocations.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// LineID string `json:"line_id,omitempty"` +// } +// +// client.ChargeUsageBasedRunCreditAllocations.Query(). +// Select(chargeusagebasedruncreditallocations.FieldLineID). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Select(fields ...string) *ChargeUsageBasedRunCreditAllocationsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedRunCreditAllocationsSelect{ChargeUsageBasedRunCreditAllocationsQuery: _q} + sbuild.label = chargeusagebasedruncreditallocations.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedRunCreditAllocationsSelect configured with the given aggregations. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunCreditAllocationsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !chargeusagebasedruncreditallocations.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBasedRunCreditAllocations, error) { + var ( + nodes = []*ChargeUsageBasedRunCreditAllocations{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBasedRunCreditAllocations).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBasedRunCreditAllocations{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withRun; query != nil { + if err := _q.loadRun(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRunCreditAllocations, e *ChargeUsageBasedRuns) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) loadRun(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBasedRunCreditAllocations, init func(*ChargeUsageBasedRunCreditAllocations), assign func(*ChargeUsageBasedRunCreditAllocations, *ChargeUsageBasedRuns)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunCreditAllocations) + for i := range nodes { + fk := nodes[i].RunID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeusagebasedruns.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedruncreditallocations.FieldID) + for i := range fields { + if fields[i] != chargeusagebasedruncreditallocations.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruncreditallocations.FieldRunID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebasedruncreditallocations.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebasedruncreditallocations.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedRunCreditAllocationsQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *ChargeUsageBasedRunCreditAllocationsQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedRunCreditAllocationsQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedRunCreditAllocationsGroupBy is the group-by builder for ChargeUsageBasedRunCreditAllocations entities. +type ChargeUsageBasedRunCreditAllocationsGroupBy struct { + selector + build *ChargeUsageBasedRunCreditAllocationsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedRunCreditAllocationsGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunCreditAllocationsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedRunCreditAllocationsGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunCreditAllocationsQuery, *ChargeUsageBasedRunCreditAllocationsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedRunCreditAllocationsGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedRunCreditAllocationsQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ChargeUsageBasedRunCreditAllocationsSelect is the builder for selecting fields of ChargeUsageBasedRunCreditAllocations entities. +type ChargeUsageBasedRunCreditAllocationsSelect struct { + *ChargeUsageBasedRunCreditAllocationsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedRunCreditAllocationsSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunCreditAllocationsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedRunCreditAllocationsSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunCreditAllocationsQuery, *ChargeUsageBasedRunCreditAllocationsSelect](ctx, _s.ChargeUsageBasedRunCreditAllocationsQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedRunCreditAllocationsSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedRunCreditAllocationsQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/openmeter/ent/db/chargeusagebasedruncreditallocations_update.go b/openmeter/ent/db/chargeusagebasedruncreditallocations_update.go new file mode 100644 index 0000000000..6c2fd8d0cd --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruncreditallocations_update.go @@ -0,0 +1,488 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunCreditAllocationsUpdate is the builder for updating ChargeUsageBasedRunCreditAllocations entities. +type ChargeUsageBasedRunCreditAllocationsUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunCreditAllocationsMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunCreditAllocationsUpdate builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) Where(ps ...predicate.ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetLineID(v string) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableLineID(v *string) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ClearLineID() *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ClearLineID() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ClearDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ClearAnnotations() *ChargeUsageBasedRunCreditAllocationsUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeUsageBasedRunCreditAllocationsMutation object of the builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) Mutation() *ChargeUsageBasedRunCreditAllocationsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruncreditallocations.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) check() error { + if v, ok := _u.mutation.LineID(); ok { + if err := chargeusagebasedruncreditallocations.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.line_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunCreditAllocations.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunCreditAllocationsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldLineID, field.TypeString, value) + } + if _u.mutation.LineIDCleared() { + _spec.ClearField(chargeusagebasedruncreditallocations.FieldLineID, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedruncreditallocations.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedruncreditallocations.FieldAnnotations, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedruncreditallocations.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedRunCreditAllocationsUpdateOne is the builder for updating a single ChargeUsageBasedRunCreditAllocations entity. +type ChargeUsageBasedRunCreditAllocationsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedRunCreditAllocationsMutation +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetLineID(v string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableLineID(v *string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ClearLineID() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ClearLineID() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ClearDeletedAt() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ClearAnnotations() *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeUsageBasedRunCreditAllocationsMutation object of the builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) Mutation() *ChargeUsageBasedRunCreditAllocationsMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunCreditAllocationsUpdate builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) Where(ps ...predicate.ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) Save(ctx context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SaveX(ctx context.Context) *ChargeUsageBasedRunCreditAllocations { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruncreditallocations.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) check() error { + if v, ok := _u.mutation.LineID(); ok { + if err := chargeusagebasedruncreditallocations.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunCreditAllocations.line_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunCreditAllocations.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunCreditAllocationsUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBasedRunCreditAllocations, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBasedRunCreditAllocations.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedruncreditallocations.FieldID) + for _, f := range fields { + if !chargeusagebasedruncreditallocations.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebasedruncreditallocations.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldLineID, field.TypeString, value) + } + if _u.mutation.LineIDCleared() { + _spec.ClearField(chargeusagebasedruncreditallocations.FieldLineID, field.TypeString) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedruncreditallocations.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedruncreditallocations.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedruncreditallocations.FieldAnnotations, field.TypeJSON) + } + _node = &ChargeUsageBasedRunCreditAllocations{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedruncreditallocations.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage.go new file mode 100644 index 0000000000..6db13356cb --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage.go @@ -0,0 +1,351 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunInvoicedUsage is the model entity for the ChargeUsageBasedRunInvoicedUsage schema. +type ChargeUsageBasedRunInvoicedUsage struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // LineID holds the value of the "line_id" field. + LineID *string `json:"line_id,omitempty"` + // ServicePeriodFrom holds the value of the "service_period_from" field. + ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` + // ServicePeriodTo holds the value of the "service_period_to" field. + ServicePeriodTo time.Time `json:"service_period_to,omitempty"` + // Mutable holds the value of the "mutable" field. + Mutable bool `json:"mutable,omitempty"` + // LedgerTransactionGroupID holds the value of the "ledger_transaction_group_id" field. + LedgerTransactionGroupID *string `json:"ledger_transaction_group_id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // TaxesTotal holds the value of the "taxes_total" field. + TaxesTotal alpacadecimal.Decimal `json:"taxes_total,omitempty"` + // TaxesInclusiveTotal holds the value of the "taxes_inclusive_total" field. + TaxesInclusiveTotal alpacadecimal.Decimal `json:"taxes_inclusive_total,omitempty"` + // TaxesExclusiveTotal holds the value of the "taxes_exclusive_total" field. + TaxesExclusiveTotal alpacadecimal.Decimal `json:"taxes_exclusive_total,omitempty"` + // ChargesTotal holds the value of the "charges_total" field. + ChargesTotal alpacadecimal.Decimal `json:"charges_total,omitempty"` + // DiscountsTotal holds the value of the "discounts_total" field. + DiscountsTotal alpacadecimal.Decimal `json:"discounts_total,omitempty"` + // CreditsTotal holds the value of the "credits_total" field. + CreditsTotal alpacadecimal.Decimal `json:"credits_total,omitempty"` + // Total holds the value of the "total" field. + Total alpacadecimal.Decimal `json:"total,omitempty"` + // RunID holds the value of the "run_id" field. + RunID string `json:"run_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedRunInvoicedUsageQuery when eager-loading is set. + Edges ChargeUsageBasedRunInvoicedUsageEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedRunInvoicedUsageEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedRunInvoicedUsageEdges struct { + // Run holds the value of the run edge. + Run *ChargeUsageBasedRuns `json:"run,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// RunOrErr returns the Run value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunInvoicedUsageEdges) RunOrErr() (*ChargeUsageBasedRuns, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeusagebasedruns.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBasedRunInvoicedUsage) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebasedruninvoicedusage.FieldAnnotations: + values[i] = new([]byte) + case chargeusagebasedruninvoicedusage.FieldAmount, chargeusagebasedruninvoicedusage.FieldTaxesTotal, chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal, chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal, chargeusagebasedruninvoicedusage.FieldChargesTotal, chargeusagebasedruninvoicedusage.FieldDiscountsTotal, chargeusagebasedruninvoicedusage.FieldCreditsTotal, chargeusagebasedruninvoicedusage.FieldTotal: + values[i] = new(alpacadecimal.Decimal) + case chargeusagebasedruninvoicedusage.FieldMutable: + values[i] = new(sql.NullBool) + case chargeusagebasedruninvoicedusage.FieldID, chargeusagebasedruninvoicedusage.FieldLineID, chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, chargeusagebasedruninvoicedusage.FieldNamespace, chargeusagebasedruninvoicedusage.FieldRunID: + values[i] = new(sql.NullString) + case chargeusagebasedruninvoicedusage.FieldServicePeriodFrom, chargeusagebasedruninvoicedusage.FieldServicePeriodTo, chargeusagebasedruninvoicedusage.FieldCreatedAt, chargeusagebasedruninvoicedusage.FieldUpdatedAt, chargeusagebasedruninvoicedusage.FieldDeletedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeUsageBasedRunInvoicedUsage fields. +func (_m *ChargeUsageBasedRunInvoicedUsage) 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) + } + for i := range columns { + switch columns[i] { + case chargeusagebasedruninvoicedusage.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case chargeusagebasedruninvoicedusage.FieldLineID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field line_id", values[i]) + } else if value.Valid { + _m.LineID = new(string) + *_m.LineID = value.String + } + case chargeusagebasedruninvoicedusage.FieldServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_from", values[i]) + } else if value.Valid { + _m.ServicePeriodFrom = value.Time + } + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_to", values[i]) + } else if value.Valid { + _m.ServicePeriodTo = value.Time + } + case chargeusagebasedruninvoicedusage.FieldMutable: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field mutable", values[i]) + } else if value.Valid { + _m.Mutable = value.Bool + } + case chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ledger_transaction_group_id", values[i]) + } else if value.Valid { + _m.LedgerTransactionGroupID = new(string) + *_m.LedgerTransactionGroupID = value.String + } + case chargeusagebasedruninvoicedusage.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + _m.Namespace = value.String + } + case chargeusagebasedruninvoicedusage.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case chargeusagebasedruninvoicedusage.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case chargeusagebasedruninvoicedusage.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = new(time.Time) + *_m.DeletedAt = value.Time + } + case chargeusagebasedruninvoicedusage.FieldAnnotations: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field annotations", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Annotations); err != nil { + return fmt.Errorf("unmarshal field annotations: %w", err) + } + } + case chargeusagebasedruninvoicedusage.FieldAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount", values[i]) + } else if value != nil { + _m.Amount = *value + } + case chargeusagebasedruninvoicedusage.FieldTaxesTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field taxes_total", values[i]) + } else if value != nil { + _m.TaxesTotal = *value + } + case chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field taxes_inclusive_total", values[i]) + } else if value != nil { + _m.TaxesInclusiveTotal = *value + } + case chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field taxes_exclusive_total", values[i]) + } else if value != nil { + _m.TaxesExclusiveTotal = *value + } + case chargeusagebasedruninvoicedusage.FieldChargesTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field charges_total", values[i]) + } else if value != nil { + _m.ChargesTotal = *value + } + case chargeusagebasedruninvoicedusage.FieldDiscountsTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field discounts_total", values[i]) + } else if value != nil { + _m.DiscountsTotal = *value + } + case chargeusagebasedruninvoicedusage.FieldCreditsTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field credits_total", values[i]) + } else if value != nil { + _m.CreditsTotal = *value + } + case chargeusagebasedruninvoicedusage.FieldTotal: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field total", values[i]) + } else if value != nil { + _m.Total = *value + } + case chargeusagebasedruninvoicedusage.FieldRunID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field run_id", values[i]) + } else if value.Valid { + _m.RunID = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeUsageBasedRunInvoicedUsage. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBasedRunInvoicedUsage) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRun queries the "run" edge of the ChargeUsageBasedRunInvoicedUsage entity. +func (_m *ChargeUsageBasedRunInvoicedUsage) QueryRun() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedRunInvoicedUsageClient(_m.config).QueryRun(_m) +} + +// Update returns a builder for updating this ChargeUsageBasedRunInvoicedUsage. +// Note that you need to call ChargeUsageBasedRunInvoicedUsage.Unwrap() before calling this method if this ChargeUsageBasedRunInvoicedUsage +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBasedRunInvoicedUsage) Update() *ChargeUsageBasedRunInvoicedUsageUpdateOne { + return NewChargeUsageBasedRunInvoicedUsageClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBasedRunInvoicedUsage 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 (_m *ChargeUsageBasedRunInvoicedUsage) Unwrap() *ChargeUsageBasedRunInvoicedUsage { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBasedRunInvoicedUsage is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBasedRunInvoicedUsage) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBasedRunInvoicedUsage(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + if v := _m.LineID; v != nil { + builder.WriteString("line_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("service_period_from=") + builder.WriteString(_m.ServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_to=") + builder.WriteString(_m.ServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("mutable=") + builder.WriteString(fmt.Sprintf("%v", _m.Mutable)) + builder.WriteString(", ") + if v := _m.LedgerTransactionGroupID; v != nil { + builder.WriteString("ledger_transaction_group_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("taxes_total=") + builder.WriteString(fmt.Sprintf("%v", _m.TaxesTotal)) + builder.WriteString(", ") + builder.WriteString("taxes_inclusive_total=") + builder.WriteString(fmt.Sprintf("%v", _m.TaxesInclusiveTotal)) + builder.WriteString(", ") + builder.WriteString("taxes_exclusive_total=") + builder.WriteString(fmt.Sprintf("%v", _m.TaxesExclusiveTotal)) + builder.WriteString(", ") + builder.WriteString("charges_total=") + builder.WriteString(fmt.Sprintf("%v", _m.ChargesTotal)) + builder.WriteString(", ") + builder.WriteString("discounts_total=") + builder.WriteString(fmt.Sprintf("%v", _m.DiscountsTotal)) + builder.WriteString(", ") + builder.WriteString("credits_total=") + builder.WriteString(fmt.Sprintf("%v", _m.CreditsTotal)) + builder.WriteString(", ") + builder.WriteString("total=") + builder.WriteString(fmt.Sprintf("%v", _m.Total)) + builder.WriteString(", ") + builder.WriteString("run_id=") + builder.WriteString(_m.RunID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunInvoicedUsages is a parsable slice of ChargeUsageBasedRunInvoicedUsage. +type ChargeUsageBasedRunInvoicedUsages []*ChargeUsageBasedRunInvoicedUsage diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage/chargeusagebasedruninvoicedusage.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage/chargeusagebasedruninvoicedusage.go new file mode 100644 index 0000000000..ccb0789ae5 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage/chargeusagebasedruninvoicedusage.go @@ -0,0 +1,229 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruninvoicedusage + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the chargeusagebasedruninvoicedusage type in the database. + Label = "charge_usage_based_run_invoiced_usage" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldServicePeriodFrom holds the string denoting the service_period_from field in the database. + FieldServicePeriodFrom = "service_period_from" + // FieldServicePeriodTo holds the string denoting the service_period_to field in the database. + FieldServicePeriodTo = "service_period_to" + // FieldMutable holds the string denoting the mutable field in the database. + FieldMutable = "mutable" + // FieldLedgerTransactionGroupID holds the string denoting the ledger_transaction_group_id field in the database. + FieldLedgerTransactionGroupID = "ledger_transaction_group_id" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldTaxesTotal holds the string denoting the taxes_total field in the database. + FieldTaxesTotal = "taxes_total" + // FieldTaxesInclusiveTotal holds the string denoting the taxes_inclusive_total field in the database. + FieldTaxesInclusiveTotal = "taxes_inclusive_total" + // FieldTaxesExclusiveTotal holds the string denoting the taxes_exclusive_total field in the database. + FieldTaxesExclusiveTotal = "taxes_exclusive_total" + // FieldChargesTotal holds the string denoting the charges_total field in the database. + FieldChargesTotal = "charges_total" + // FieldDiscountsTotal holds the string denoting the discounts_total field in the database. + FieldDiscountsTotal = "discounts_total" + // FieldCreditsTotal holds the string denoting the credits_total field in the database. + FieldCreditsTotal = "credits_total" + // FieldTotal holds the string denoting the total field in the database. + FieldTotal = "total" + // FieldRunID holds the string denoting the run_id field in the database. + FieldRunID = "run_id" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // Table holds the table name of the chargeusagebasedruninvoicedusage in the database. + Table = "charge_usage_based_run_invoiced_usages" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_usage_based_run_invoiced_usages" + // RunInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + RunInverseTable = "charge_usage_based_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" +) + +// Columns holds all SQL columns for chargeusagebasedruninvoicedusage fields. +var Columns = []string{ + FieldID, + FieldLineID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldMutable, + FieldLedgerTransactionGroupID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldAmount, + FieldTaxesTotal, + FieldTaxesInclusiveTotal, + FieldTaxesExclusiveTotal, + FieldChargesTotal, + FieldDiscountsTotal, + FieldCreditsTotal, + FieldTotal, + FieldRunID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // LineIDValidator is a validator for the "line_id" field. It is called by the builders before save. + LineIDValidator func(string) error + // LedgerTransactionGroupIDValidator is a validator for the "ledger_transaction_group_id" field. It is called by the builders before save. + LedgerTransactionGroupIDValidator func(string) error + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// OrderOption defines the ordering options for the ChargeUsageBasedRunInvoicedUsage 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() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByServicePeriodFrom orders the results by the service_period_from field. +func ByServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodFrom, opts...).ToFunc() +} + +// ByServicePeriodTo orders the results by the service_period_to field. +func ByServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodTo, opts...).ToFunc() +} + +// ByMutable orders the results by the mutable field. +func ByMutable(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMutable, opts...).ToFunc() +} + +// ByLedgerTransactionGroupID orders the results by the ledger_transaction_group_id field. +func ByLedgerTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLedgerTransactionGroupID, opts...).ToFunc() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByTaxesTotal orders the results by the taxes_total field. +func ByTaxesTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxesTotal, opts...).ToFunc() +} + +// ByTaxesInclusiveTotal orders the results by the taxes_inclusive_total field. +func ByTaxesInclusiveTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxesInclusiveTotal, opts...).ToFunc() +} + +// ByTaxesExclusiveTotal orders the results by the taxes_exclusive_total field. +func ByTaxesExclusiveTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaxesExclusiveTotal, opts...).ToFunc() +} + +// ByChargesTotal orders the results by the charges_total field. +func ByChargesTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargesTotal, opts...).ToFunc() +} + +// ByDiscountsTotal orders the results by the discounts_total field. +func ByDiscountsTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDiscountsTotal, opts...).ToFunc() +} + +// ByCreditsTotal orders the results by the credits_total field. +func ByCreditsTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreditsTotal, opts...).ToFunc() +} + +// ByTotal orders the results by the total field. +func ByTotal(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotal, opts...).ToFunc() +} + +// ByRunID orders the results by the run_id field. +func ByRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRunID, opts...).ToFunc() +} + +// ByRunField orders the results by run field. +func ByRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRunStep(), sql.OrderByField(field, opts...)) + } +} +func newRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, RunTable, RunColumn), + ) +} diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage/where.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage/where.go new file mode 100644 index 0000000000..8b727b0698 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage/where.go @@ -0,0 +1,1025 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruninvoicedusage + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContainsFold(FieldID, id)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldLineID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodTo applies equality check predicate on the "service_period_to" field. It's identical to ServicePeriodToEQ. +func ServicePeriodTo(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// Mutable applies equality check predicate on the "mutable" field. It's identical to MutableEQ. +func Mutable(v bool) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldMutable, v)) +} + +// LedgerTransactionGroupID applies equality check predicate on the "ledger_transaction_group_id" field. It's identical to LedgerTransactionGroupIDEQ. +func LedgerTransactionGroupID(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldNamespace, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldDeletedAt, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldAmount, v)) +} + +// TaxesTotal applies equality check predicate on the "taxes_total" field. It's identical to TaxesTotalEQ. +func TaxesTotal(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotal applies equality check predicate on the "taxes_inclusive_total" field. It's identical to TaxesInclusiveTotalEQ. +func TaxesInclusiveTotal(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotal applies equality check predicate on the "taxes_exclusive_total" field. It's identical to TaxesExclusiveTotalEQ. +func TaxesExclusiveTotal(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotal applies equality check predicate on the "charges_total" field. It's identical to ChargesTotalEQ. +func ChargesTotal(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldChargesTotal, v)) +} + +// DiscountsTotal applies equality check predicate on the "discounts_total" field. It's identical to DiscountsTotalEQ. +func DiscountsTotal(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// CreditsTotal applies equality check predicate on the "credits_total" field. It's identical to CreditsTotalEQ. +func CreditsTotal(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// Total applies equality check predicate on the "total" field. It's identical to TotalEQ. +func Total(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTotal, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldRunID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDIsNil applies the IsNil predicate on the "line_id" field. +func LineIDIsNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIsNull(FieldLineID)) +} + +// LineIDNotNil applies the NotNil predicate on the "line_id" field. +func LineIDNotNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotNull(FieldLineID)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContainsFold(FieldLineID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// MutableEQ applies the EQ predicate on the "mutable" field. +func MutableEQ(v bool) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldMutable, v)) +} + +// MutableNEQ applies the NEQ predicate on the "mutable" field. +func MutableNEQ(v bool) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldMutable, v)) +} + +// LedgerTransactionGroupIDEQ applies the EQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDNEQ applies the NEQ predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDIn applies the In predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDNotIn applies the NotIn predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNotIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldLedgerTransactionGroupID, vs...)) +} + +// LedgerTransactionGroupIDGT applies the GT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDGTE applies the GTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDGTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLT applies the LT predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDLTE applies the LTE predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDLTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContains applies the Contains predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContains(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContains(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasPrefix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasPrefix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDHasSuffix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasSuffix(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDIsNil applies the IsNil predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDIsNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIsNull(FieldLedgerTransactionGroupID)) +} + +// LedgerTransactionGroupIDNotNil applies the NotNil predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDNotNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotNull(FieldLedgerTransactionGroupID)) +} + +// LedgerTransactionGroupIDEqualFold applies the EqualFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDEqualFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEqualFold(FieldLedgerTransactionGroupID, v)) +} + +// LedgerTransactionGroupIDContainsFold applies the ContainsFold predicate on the "ledger_transaction_group_id" field. +func LedgerTransactionGroupIDContainsFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContainsFold(FieldLedgerTransactionGroupID, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotNull(FieldAnnotations)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldAmount, v)) +} + +// TaxesTotalEQ applies the EQ predicate on the "taxes_total" field. +func TaxesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalNEQ applies the NEQ predicate on the "taxes_total" field. +func TaxesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldTaxesTotal, v)) +} + +// TaxesTotalIn applies the In predicate on the "taxes_total" field. +func TaxesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalNotIn applies the NotIn predicate on the "taxes_total" field. +func TaxesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldTaxesTotal, vs...)) +} + +// TaxesTotalGT applies the GT predicate on the "taxes_total" field. +func TaxesTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldTaxesTotal, v)) +} + +// TaxesTotalGTE applies the GTE predicate on the "taxes_total" field. +func TaxesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldTaxesTotal, v)) +} + +// TaxesTotalLT applies the LT predicate on the "taxes_total" field. +func TaxesTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldTaxesTotal, v)) +} + +// TaxesTotalLTE applies the LTE predicate on the "taxes_total" field. +func TaxesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldTaxesTotal, v)) +} + +// TaxesInclusiveTotalEQ applies the EQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalNEQ applies the NEQ predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalIn applies the In predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalNotIn applies the NotIn predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldTaxesInclusiveTotal, vs...)) +} + +// TaxesInclusiveTotalGT applies the GT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalGTE applies the GTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLT applies the LT predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldTaxesInclusiveTotal, v)) +} + +// TaxesInclusiveTotalLTE applies the LTE predicate on the "taxes_inclusive_total" field. +func TaxesInclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldTaxesInclusiveTotal, v)) +} + +// TaxesExclusiveTotalEQ applies the EQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalNEQ applies the NEQ predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalIn applies the In predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalNotIn applies the NotIn predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldTaxesExclusiveTotal, vs...)) +} + +// TaxesExclusiveTotalGT applies the GT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalGTE applies the GTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLT applies the LT predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldTaxesExclusiveTotal, v)) +} + +// TaxesExclusiveTotalLTE applies the LTE predicate on the "taxes_exclusive_total" field. +func TaxesExclusiveTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldTaxesExclusiveTotal, v)) +} + +// ChargesTotalEQ applies the EQ predicate on the "charges_total" field. +func ChargesTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldChargesTotal, v)) +} + +// ChargesTotalNEQ applies the NEQ predicate on the "charges_total" field. +func ChargesTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldChargesTotal, v)) +} + +// ChargesTotalIn applies the In predicate on the "charges_total" field. +func ChargesTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalNotIn applies the NotIn predicate on the "charges_total" field. +func ChargesTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldChargesTotal, vs...)) +} + +// ChargesTotalGT applies the GT predicate on the "charges_total" field. +func ChargesTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldChargesTotal, v)) +} + +// ChargesTotalGTE applies the GTE predicate on the "charges_total" field. +func ChargesTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldChargesTotal, v)) +} + +// ChargesTotalLT applies the LT predicate on the "charges_total" field. +func ChargesTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldChargesTotal, v)) +} + +// ChargesTotalLTE applies the LTE predicate on the "charges_total" field. +func ChargesTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldChargesTotal, v)) +} + +// DiscountsTotalEQ applies the EQ predicate on the "discounts_total" field. +func DiscountsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalNEQ applies the NEQ predicate on the "discounts_total" field. +func DiscountsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldDiscountsTotal, v)) +} + +// DiscountsTotalIn applies the In predicate on the "discounts_total" field. +func DiscountsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalNotIn applies the NotIn predicate on the "discounts_total" field. +func DiscountsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldDiscountsTotal, vs...)) +} + +// DiscountsTotalGT applies the GT predicate on the "discounts_total" field. +func DiscountsTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalGTE applies the GTE predicate on the "discounts_total" field. +func DiscountsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLT applies the LT predicate on the "discounts_total" field. +func DiscountsTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldDiscountsTotal, v)) +} + +// DiscountsTotalLTE applies the LTE predicate on the "discounts_total" field. +func DiscountsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldDiscountsTotal, v)) +} + +// CreditsTotalEQ applies the EQ predicate on the "credits_total" field. +func CreditsTotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalNEQ applies the NEQ predicate on the "credits_total" field. +func CreditsTotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldCreditsTotal, v)) +} + +// CreditsTotalIn applies the In predicate on the "credits_total" field. +func CreditsTotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalNotIn applies the NotIn predicate on the "credits_total" field. +func CreditsTotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldCreditsTotal, vs...)) +} + +// CreditsTotalGT applies the GT predicate on the "credits_total" field. +func CreditsTotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldCreditsTotal, v)) +} + +// CreditsTotalGTE applies the GTE predicate on the "credits_total" field. +func CreditsTotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldCreditsTotal, v)) +} + +// CreditsTotalLT applies the LT predicate on the "credits_total" field. +func CreditsTotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldCreditsTotal, v)) +} + +// CreditsTotalLTE applies the LTE predicate on the "credits_total" field. +func CreditsTotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldCreditsTotal, v)) +} + +// TotalEQ applies the EQ predicate on the "total" field. +func TotalEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldTotal, v)) +} + +// TotalNEQ applies the NEQ predicate on the "total" field. +func TotalNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldTotal, v)) +} + +// TotalIn applies the In predicate on the "total" field. +func TotalIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldTotal, vs...)) +} + +// TotalNotIn applies the NotIn predicate on the "total" field. +func TotalNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldTotal, vs...)) +} + +// TotalGT applies the GT predicate on the "total" field. +func TotalGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldTotal, v)) +} + +// TotalGTE applies the GTE predicate on the "total" field. +func TotalGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldTotal, v)) +} + +// TotalLT applies the LT predicate on the "total" field. +func TotalLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldTotal, v)) +} + +// TotalLTE applies the LTE predicate on the "total" field. +func TotalLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldTotal, v)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.FieldContainsFold(FieldRunID, v)) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, RunTable, RunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRunWith applies the HasEdge predicate on the "run" edge with a given conditions (other predicates). +func HasRunWith(preds ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(func(s *sql.Selector) { + step := newRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ChargeUsageBasedRunInvoicedUsage) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBasedRunInvoicedUsage) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBasedRunInvoicedUsage) predicate.ChargeUsageBasedRunInvoicedUsage { + return predicate.ChargeUsageBasedRunInvoicedUsage(sql.NotPredicates(p)) +} diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage_create.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage_create.go new file mode 100644 index 0000000000..0ff15fdbc1 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage_create.go @@ -0,0 +1,1515 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunInvoicedUsageCreate is the builder for creating a ChargeUsageBasedRunInvoicedUsage entity. +type ChargeUsageBasedRunInvoicedUsageCreate struct { + config + mutation *ChargeUsageBasedRunInvoicedUsageMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetLineID(v string) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNillableLineID(v *string) *ChargeUsageBasedRunInvoicedUsageCreate { + if v != nil { + _c.SetLineID(*v) + } + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetMutable sets the "mutable" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetMutable(v bool) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetMutable(v) + return _c +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetLedgerTransactionGroupID(v) + return _c +} + +// SetNillableLedgerTransactionGroupID sets the "ledger_transaction_group_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNillableLedgerTransactionGroupID(v *string) *ChargeUsageBasedRunInvoicedUsageCreate { + if v != nil { + _c.SetLedgerTransactionGroupID(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNamespace(v string) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetCreatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNillableCreatedAt(v *time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNillableUpdatedAt(v *time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunInvoicedUsageCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetTaxesTotal(v) + return _c +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetTaxesInclusiveTotal(v) + return _c +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetTaxesExclusiveTotal(v) + return _c +} + +// SetChargesTotal sets the "charges_total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetChargesTotal(v) + return _c +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetDiscountsTotal(v) + return _c +} + +// SetCreditsTotal sets the "credits_total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetCreditsTotal(v) + return _c +} + +// SetTotal sets the "total" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetTotal(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetRunID(v string) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetID(v string) *ChargeUsageBasedRunInvoicedUsageCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetNillableID(v *string) *ChargeUsageBasedRunInvoicedUsageCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRun sets the "run" edge to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SetRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunInvoicedUsageCreate { + return _c.SetRunID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunInvoicedUsageMutation object of the builder. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) Mutation() *ChargeUsageBasedRunInvoicedUsageMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBasedRunInvoicedUsage in the database. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) Save(ctx context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) SaveX(ctx context.Context) *ChargeUsageBasedRunInvoicedUsage { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeusagebasedruninvoicedusage.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruninvoicedusage.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebasedruninvoicedusage.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) check() error { + if v, ok := _c.mutation.LineID(); ok { + if err := chargeusagebasedruninvoicedusage.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.line_id": %w`, err)} + } + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.service_period_to"`)} + } + if _, ok := _c.mutation.Mutable(); !ok { + return &ValidationError{Name: "mutable", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.mutable"`)} + } + if v, ok := _c.mutation.LedgerTransactionGroupID(); ok { + if err := chargeusagebasedruninvoicedusage.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.ledger_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebasedruninvoicedusage.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.updated_at"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.amount"`)} + } + if _, ok := _c.mutation.TaxesTotal(); !ok { + return &ValidationError{Name: "taxes_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.taxes_total"`)} + } + if _, ok := _c.mutation.TaxesInclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_inclusive_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.taxes_inclusive_total"`)} + } + if _, ok := _c.mutation.TaxesExclusiveTotal(); !ok { + return &ValidationError{Name: "taxes_exclusive_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.taxes_exclusive_total"`)} + } + if _, ok := _c.mutation.ChargesTotal(); !ok { + return &ValidationError{Name: "charges_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.charges_total"`)} + } + if _, ok := _c.mutation.DiscountsTotal(); !ok { + return &ValidationError{Name: "discounts_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.discounts_total"`)} + } + if _, ok := _c.mutation.CreditsTotal(); !ok { + return &ValidationError{Name: "credits_total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.credits_total"`)} + } + if _, ok := _c.mutation.Total(); !ok { + return &ValidationError{Name: "total", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.total"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunInvoicedUsage.run_id"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeUsageBasedRunInvoicedUsage.run"`)} + } + return nil +} + +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) sqlSave(ctx context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected ChargeUsageBasedRunInvoicedUsage.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) createSpec() (*ChargeUsageBasedRunInvoicedUsage, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeUsageBasedRunInvoicedUsage{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebasedruninvoicedusage.Table, sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldLineID, field.TypeString, value) + _node.LineID = &value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.Mutable(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldMutable, field.TypeBool, value) + _node.Mutable = value + } + if value, ok := _c.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString, value) + _node.LedgerTransactionGroupID = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesTotal, field.TypeOther, value) + _node.TaxesTotal = value + } + if value, ok := _c.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal, field.TypeOther, value) + _node.TaxesInclusiveTotal = value + } + if value, ok := _c.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal, field.TypeOther, value) + _node.TaxesExclusiveTotal = value + } + if value, ok := _c.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldChargesTotal, field.TypeOther, value) + _node.ChargesTotal = value + } + if value, ok := _c.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldDiscountsTotal, field.TypeOther, value) + _node.DiscountsTotal = value + } + if value, ok := _c.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldCreditsTotal, field.TypeOther, value) + _node.CreditsTotal = value + } + if value, ok := _c.mutation.Total(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTotal, field.TypeOther, value) + _node.Total = value + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedruninvoicedusage.RunTable, + Columns: []string{chargeusagebasedruninvoicedusage.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RunID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// SetLineID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunInvoicedUsageUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedRunInvoicedUsageUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunInvoicedUsageCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunInvoicedUsageUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedRunInvoicedUsageUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBasedRunInvoicedUsage node. + ChargeUsageBasedRunInvoicedUsageUpsertOne struct { + create *ChargeUsageBasedRunInvoicedUsageCreate + } + + // ChargeUsageBasedRunInvoicedUsageUpsert is the "OnConflict" setter. + ChargeUsageBasedRunInvoicedUsageUpsert struct { + *sql.UpdateSet + } +) + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetLineID(v string) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldLineID, v) + return u +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateLineID() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldLineID) + return u +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) ClearLineID() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetNull(chargeusagebasedruninvoicedusage.FieldLineID) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateServicePeriodFrom() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateServicePeriodTo() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldServicePeriodTo) + return u +} + +// SetMutable sets the "mutable" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetMutable(v bool) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldMutable, v) + return u +} + +// UpdateMutable sets the "mutable" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateMutable() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldMutable) + return u +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, v) + return u +} + +// UpdateLedgerTransactionGroupID sets the "ledger_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID) + return u +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) ClearLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetNull(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateUpdatedAt() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetDeletedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) ClearDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetNull(chargeusagebasedruninvoicedusage.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateAnnotations() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) ClearAnnotations() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetNull(chargeusagebasedruninvoicedusage.FieldAnnotations) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateAmount() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldAmount) + return u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldTaxesTotal, v) + return u +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateTaxesTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldTaxesTotal) + return u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal, v) + return u +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal) + return u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal, v) + return u +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal) + return u +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldChargesTotal, v) + return u +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateChargesTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldChargesTotal) + return u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldDiscountsTotal, v) + return u +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateDiscountsTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldDiscountsTotal) + return u +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldCreditsTotal, v) + return u +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateCreditsTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldCreditsTotal) + return u +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsert { + u.Set(chargeusagebasedruninvoicedusage.FieldTotal, v) + return u +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsert) UpdateTotal() *ChargeUsageBasedRunInvoicedUsageUpsert { + u.SetExcluded(chargeusagebasedruninvoicedusage.FieldTotal) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedruninvoicedusage.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateNewValues() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) Ignore() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) DoNothing() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunInvoicedUsageCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) Update(set func(*ChargeUsageBasedRunInvoicedUsageUpsert)) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunInvoicedUsageUpsert{UpdateSet: update}) + })) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetLineID(v string) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateLineID() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) ClearLineID() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearLineID() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateServicePeriodFrom() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateServicePeriodTo() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetMutable sets the "mutable" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetMutable(v bool) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetMutable(v) + }) +} + +// UpdateMutable sets the "mutable" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateMutable() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateMutable() + }) +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetLedgerTransactionGroupID(v) + }) +} + +// UpdateLedgerTransactionGroupID sets the "ledger_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateLedgerTransactionGroupID() + }) +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) ClearLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearLedgerTransactionGroupID() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateUpdatedAt() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) ClearDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateAnnotations() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) ClearAnnotations() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearAnnotations() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateAmount() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateTaxesTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateChargesTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateDiscountsTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateCreditsTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) UpdateTotal() *ChargeUsageBasedRunInvoicedUsageUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTotal() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunInvoicedUsageCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: ChargeUsageBasedRunInvoicedUsageUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedRunInvoicedUsageUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedRunInvoicedUsageCreateBulk is the builder for creating many ChargeUsageBasedRunInvoicedUsage entities in bulk. +type ChargeUsageBasedRunInvoicedUsageCreateBulk struct { + config + err error + builders []*ChargeUsageBasedRunInvoicedUsageCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBasedRunInvoicedUsage entities in the database. +func (_c *ChargeUsageBasedRunInvoicedUsageCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBasedRunInvoicedUsage, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBasedRunInvoicedUsage, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ChargeUsageBasedRunInvoicedUsageMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ChargeUsageBasedRunInvoicedUsageCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBasedRunInvoicedUsage { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunInvoicedUsageCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunInvoicedUsageCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRunInvoicedUsage.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunInvoicedUsageUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunInvoicedUsageCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedRunInvoicedUsageUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunInvoicedUsageCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunInvoicedUsageUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedRunInvoicedUsageUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBasedRunInvoicedUsage nodes. +type ChargeUsageBasedRunInvoicedUsageUpsertBulk struct { + create *ChargeUsageBasedRunInvoicedUsageCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedruninvoicedusage.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateNewValues() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeusagebasedruninvoicedusage.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunInvoicedUsage.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) Ignore() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) DoNothing() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunInvoicedUsageCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) Update(set func(*ChargeUsageBasedRunInvoicedUsageUpsert)) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunInvoicedUsageUpsert{UpdateSet: update}) + })) + return u +} + +// SetLineID sets the "line_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetLineID(v string) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetLineID(v) + }) +} + +// UpdateLineID sets the "line_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateLineID() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateLineID() + }) +} + +// ClearLineID clears the value of the "line_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) ClearLineID() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearLineID() + }) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateServicePeriodFrom() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateServicePeriodTo() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetMutable sets the "mutable" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetMutable(v bool) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetMutable(v) + }) +} + +// UpdateMutable sets the "mutable" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateMutable() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateMutable() + }) +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetLedgerTransactionGroupID(v) + }) +} + +// UpdateLedgerTransactionGroupID sets the "ledger_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateLedgerTransactionGroupID() + }) +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) ClearLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearLedgerTransactionGroupID() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateUpdatedAt() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetDeletedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) ClearDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateAnnotations() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) ClearAnnotations() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.ClearAnnotations() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateAmount() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateAmount() + }) +} + +// SetTaxesTotal sets the "taxes_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTaxesTotal(v) + }) +} + +// UpdateTaxesTotal sets the "taxes_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateTaxesTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTaxesTotal() + }) +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTaxesInclusiveTotal(v) + }) +} + +// UpdateTaxesInclusiveTotal sets the "taxes_inclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateTaxesInclusiveTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTaxesInclusiveTotal() + }) +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTaxesExclusiveTotal(v) + }) +} + +// UpdateTaxesExclusiveTotal sets the "taxes_exclusive_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateTaxesExclusiveTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTaxesExclusiveTotal() + }) +} + +// SetChargesTotal sets the "charges_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetChargesTotal(v) + }) +} + +// UpdateChargesTotal sets the "charges_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateChargesTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateChargesTotal() + }) +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetDiscountsTotal(v) + }) +} + +// UpdateDiscountsTotal sets the "discounts_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateDiscountsTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateDiscountsTotal() + }) +} + +// SetCreditsTotal sets the "credits_total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetCreditsTotal(v) + }) +} + +// UpdateCreditsTotal sets the "credits_total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateCreditsTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateCreditsTotal() + }) +} + +// SetTotal sets the "total" field. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.SetTotal(v) + }) +} + +// UpdateTotal sets the "total" field to the value that was provided on create. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) UpdateTotal() *ChargeUsageBasedRunInvoicedUsageUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunInvoicedUsageUpsert) { + s.UpdateTotal() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ChargeUsageBasedRunInvoicedUsageCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunInvoicedUsageCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunInvoicedUsageUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage_delete.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage_delete.go new file mode 100644 index 0000000000..e4c9b4beb0 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunInvoicedUsageDelete is the builder for deleting a ChargeUsageBasedRunInvoicedUsage entity. +type ChargeUsageBasedRunInvoicedUsageDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunInvoicedUsageMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunInvoicedUsageDelete builder. +func (_d *ChargeUsageBasedRunInvoicedUsageDelete) Where(ps ...predicate.ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedRunInvoicedUsageDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunInvoicedUsageDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedRunInvoicedUsageDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebasedruninvoicedusage.Table, sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ChargeUsageBasedRunInvoicedUsageDeleteOne is the builder for deleting a single ChargeUsageBasedRunInvoicedUsage entity. +type ChargeUsageBasedRunInvoicedUsageDeleteOne struct { + _d *ChargeUsageBasedRunInvoicedUsageDelete +} + +// Where appends a list predicates to the ChargeUsageBasedRunInvoicedUsageDelete builder. +func (_d *ChargeUsageBasedRunInvoicedUsageDeleteOne) Where(ps ...predicate.ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedRunInvoicedUsageDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebasedruninvoicedusage.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunInvoicedUsageDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage_query.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage_query.go new file mode 100644 index 0000000000..d2ad613523 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage_query.go @@ -0,0 +1,643 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunInvoicedUsageQuery is the builder for querying ChargeUsageBasedRunInvoicedUsage entities. +type ChargeUsageBasedRunInvoicedUsageQuery struct { + config + ctx *QueryContext + order []chargeusagebasedruninvoicedusage.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBasedRunInvoicedUsage + withRun *ChargeUsageBasedRunsQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ChargeUsageBasedRunInvoicedUsageQuery builder. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Where(ps ...predicate.ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Limit(limit int) *ChargeUsageBasedRunInvoicedUsageQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Offset(offset int) *ChargeUsageBasedRunInvoicedUsageQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ChargeUsageBasedRunInvoicedUsageQuery) Unique(unique bool) *ChargeUsageBasedRunInvoicedUsageQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Order(o ...chargeusagebasedruninvoicedusage.OrderOption) *ChargeUsageBasedRunInvoicedUsageQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) QueryRun() *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedruninvoicedusage.RunTable, chargeusagebasedruninvoicedusage.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBasedRunInvoicedUsage entity from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunInvoicedUsage was found. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) First(ctx context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{chargeusagebasedruninvoicedusage.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) FirstX(ctx context.Context) *ChargeUsageBasedRunInvoicedUsage { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBasedRunInvoicedUsage ID from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunInvoicedUsage ID was found. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{chargeusagebasedruninvoicedusage.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBasedRunInvoicedUsage entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunInvoicedUsage entity is found. +// Returns a *NotFoundError when no ChargeUsageBasedRunInvoicedUsage entities are found. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Only(ctx context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{chargeusagebasedruninvoicedusage.Label} + default: + return nil, &NotSingularError{chargeusagebasedruninvoicedusage.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) OnlyX(ctx context.Context) *ChargeUsageBasedRunInvoicedUsage { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBasedRunInvoicedUsage ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunInvoicedUsage ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{chargeusagebasedruninvoicedusage.Label} + default: + err = &NotSingularError{chargeusagebasedruninvoicedusage.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ChargeUsageBasedRunInvoicedUsages. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) All(ctx context.Context) ([]*ChargeUsageBasedRunInvoicedUsage, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBasedRunInvoicedUsage, *ChargeUsageBasedRunInvoicedUsageQuery]() + return withInterceptors[[]*ChargeUsageBasedRunInvoicedUsage](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) AllX(ctx context.Context) []*ChargeUsageBasedRunInvoicedUsage { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBasedRunInvoicedUsage IDs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(chargeusagebasedruninvoicedusage.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ChargeUsageBasedRunInvoicedUsageQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedRunInvoicedUsageQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Clone() *ChargeUsageBasedRunInvoicedUsageQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedRunInvoicedUsageQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebasedruninvoicedusage.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBasedRunInvoicedUsage{}, _q.predicates...), + withRun: _q.withRun.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithRun tells the query-builder to eager-load the nodes that are connected to +// the "run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) WithRun(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedRunInvoicedUsageQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRun = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// LineID string `json:"line_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBasedRunInvoicedUsage.Query(). +// GroupBy(chargeusagebasedruninvoicedusage.FieldLineID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedRunInvoicedUsageGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedRunInvoicedUsageGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebasedruninvoicedusage.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// LineID string `json:"line_id,omitempty"` +// } +// +// client.ChargeUsageBasedRunInvoicedUsage.Query(). +// Select(chargeusagebasedruninvoicedusage.FieldLineID). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Select(fields ...string) *ChargeUsageBasedRunInvoicedUsageSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedRunInvoicedUsageSelect{ChargeUsageBasedRunInvoicedUsageQuery: _q} + sbuild.label = chargeusagebasedruninvoicedusage.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedRunInvoicedUsageSelect configured with the given aggregations. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunInvoicedUsageSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !chargeusagebasedruninvoicedusage.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBasedRunInvoicedUsage, error) { + var ( + nodes = []*ChargeUsageBasedRunInvoicedUsage{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBasedRunInvoicedUsage).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBasedRunInvoicedUsage{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withRun; query != nil { + if err := _q.loadRun(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRunInvoicedUsage, e *ChargeUsageBasedRuns) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) loadRun(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBasedRunInvoicedUsage, init func(*ChargeUsageBasedRunInvoicedUsage), assign func(*ChargeUsageBasedRunInvoicedUsage, *ChargeUsageBasedRuns)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunInvoicedUsage) + for i := range nodes { + fk := nodes[i].RunID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeusagebasedruns.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedruninvoicedusage.FieldID) + for i := range fields { + if fields[i] != chargeusagebasedruninvoicedusage.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruninvoicedusage.FieldRunID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebasedruninvoicedusage.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebasedruninvoicedusage.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedRunInvoicedUsageQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *ChargeUsageBasedRunInvoicedUsageQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedRunInvoicedUsageQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedRunInvoicedUsageGroupBy is the group-by builder for ChargeUsageBasedRunInvoicedUsage entities. +type ChargeUsageBasedRunInvoicedUsageGroupBy struct { + selector + build *ChargeUsageBasedRunInvoicedUsageQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedRunInvoicedUsageGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunInvoicedUsageGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedRunInvoicedUsageGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunInvoicedUsageQuery, *ChargeUsageBasedRunInvoicedUsageGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedRunInvoicedUsageGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedRunInvoicedUsageQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ChargeUsageBasedRunInvoicedUsageSelect is the builder for selecting fields of ChargeUsageBasedRunInvoicedUsage entities. +type ChargeUsageBasedRunInvoicedUsageSelect struct { + *ChargeUsageBasedRunInvoicedUsageQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedRunInvoicedUsageSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunInvoicedUsageSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedRunInvoicedUsageSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunInvoicedUsageQuery, *ChargeUsageBasedRunInvoicedUsageSelect](ctx, _s.ChargeUsageBasedRunInvoicedUsageQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedRunInvoicedUsageSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedRunInvoicedUsageQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/openmeter/ent/db/chargeusagebasedruninvoicedusage_update.go b/openmeter/ent/db/chargeusagebasedruninvoicedusage_update.go new file mode 100644 index 0000000000..9d632ec59a --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruninvoicedusage_update.go @@ -0,0 +1,822 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunInvoicedUsageUpdate is the builder for updating ChargeUsageBasedRunInvoicedUsage entities. +type ChargeUsageBasedRunInvoicedUsageUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunInvoicedUsageMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunInvoicedUsageUpdate builder. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) Where(ps ...predicate.ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetLineID(v string) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableLineID(v *string) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) ClearLineID() *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.ClearLineID() + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetMutable sets the "mutable" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetMutable(v bool) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetMutable(v) + return _u +} + +// SetNillableMutable sets the "mutable" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableMutable(v *bool) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetMutable(*v) + } + return _u +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetLedgerTransactionGroupID(v) + return _u +} + +// SetNillableLedgerTransactionGroupID sets the "ledger_transaction_group_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableLedgerTransactionGroupID(v *string) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetLedgerTransactionGroupID(*v) + } + return _u +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) ClearLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.ClearLedgerTransactionGroupID() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) ClearDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) ClearAnnotations() *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdate { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// Mutation returns the ChargeUsageBasedRunInvoicedUsageMutation object of the builder. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) Mutation() *ChargeUsageBasedRunInvoicedUsageMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruninvoicedusage.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) check() error { + if v, ok := _u.mutation.LineID(); ok { + if err := chargeusagebasedruninvoicedusage.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.line_id": %w`, err)} + } + } + if v, ok := _u.mutation.LedgerTransactionGroupID(); ok { + if err := chargeusagebasedruninvoicedusage.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.ledger_transaction_group_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunInvoicedUsage.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunInvoicedUsageUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldLineID, field.TypeString, value) + } + if _u.mutation.LineIDCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldLineID, field.TypeString) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Mutable(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldMutable, field.TypeBool, value) + } + if value, ok := _u.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString, value) + } + if _u.mutation.LedgerTransactionGroupIDCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTotal, field.TypeOther, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedruninvoicedusage.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedRunInvoicedUsageUpdateOne is the builder for updating a single ChargeUsageBasedRunInvoicedUsage entity. +type ChargeUsageBasedRunInvoicedUsageUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedRunInvoicedUsageMutation +} + +// SetLineID sets the "line_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetLineID(v string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetLineID(v) + return _u +} + +// SetNillableLineID sets the "line_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableLineID(v *string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetLineID(*v) + } + return _u +} + +// ClearLineID clears the value of the "line_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) ClearLineID() *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.ClearLineID() + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetMutable sets the "mutable" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetMutable(v bool) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetMutable(v) + return _u +} + +// SetNillableMutable sets the "mutable" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableMutable(v *bool) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetMutable(*v) + } + return _u +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetLedgerTransactionGroupID(v string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetLedgerTransactionGroupID(v) + return _u +} + +// SetNillableLedgerTransactionGroupID sets the "ledger_transaction_group_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableLedgerTransactionGroupID(v *string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetLedgerTransactionGroupID(*v) + } + return _u +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) ClearLedgerTransactionGroupID() *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.ClearLedgerTransactionGroupID() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) ClearDeletedAt() *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) ClearAnnotations() *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetTaxesTotal sets the "taxes_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetTaxesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetTaxesTotal(v) + return _u +} + +// SetNillableTaxesTotal sets the "taxes_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableTaxesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTaxesTotal(*v) + } + return _u +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetTaxesInclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetTaxesInclusiveTotal(v) + return _u +} + +// SetNillableTaxesInclusiveTotal sets the "taxes_inclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableTaxesInclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTaxesInclusiveTotal(*v) + } + return _u +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetTaxesExclusiveTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetTaxesExclusiveTotal(v) + return _u +} + +// SetNillableTaxesExclusiveTotal sets the "taxes_exclusive_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableTaxesExclusiveTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTaxesExclusiveTotal(*v) + } + return _u +} + +// SetChargesTotal sets the "charges_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetChargesTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetChargesTotal(v) + return _u +} + +// SetNillableChargesTotal sets the "charges_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableChargesTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetChargesTotal(*v) + } + return _u +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetDiscountsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetDiscountsTotal(v) + return _u +} + +// SetNillableDiscountsTotal sets the "discounts_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableDiscountsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetDiscountsTotal(*v) + } + return _u +} + +// SetCreditsTotal sets the "credits_total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetCreditsTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetCreditsTotal(v) + return _u +} + +// SetNillableCreditsTotal sets the "credits_total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableCreditsTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetCreditsTotal(*v) + } + return _u +} + +// SetTotal sets the "total" field. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetTotal(v alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.SetTotal(v) + return _u +} + +// SetNillableTotal sets the "total" field if the given value is not nil. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetNillableTotal(v *alpacadecimal.Decimal) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if v != nil { + _u.SetTotal(*v) + } + return _u +} + +// Mutation returns the ChargeUsageBasedRunInvoicedUsageMutation object of the builder. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) Mutation() *ChargeUsageBasedRunInvoicedUsageMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunInvoicedUsageUpdate builder. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) Where(ps ...predicate.ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBasedRunInvoicedUsage entity. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) Save(ctx context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SaveX(ctx context.Context) *ChargeUsageBasedRunInvoicedUsage { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruninvoicedusage.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) check() error { + if v, ok := _u.mutation.LineID(); ok { + if err := chargeusagebasedruninvoicedusage.LineIDValidator(v); err != nil { + return &ValidationError{Name: "line_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.line_id": %w`, err)} + } + } + if v, ok := _u.mutation.LedgerTransactionGroupID(); ok { + if err := chargeusagebasedruninvoicedusage.LedgerTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "ledger_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunInvoicedUsage.ledger_transaction_group_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunInvoicedUsage.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunInvoicedUsageUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBasedRunInvoicedUsage, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBasedRunInvoicedUsage.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedruninvoicedusage.FieldID) + for _, f := range fields { + if !chargeusagebasedruninvoicedusage.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebasedruninvoicedusage.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldLineID, field.TypeString, value) + } + if _u.mutation.LineIDCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldLineID, field.TypeString) + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Mutable(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldMutable, field.TypeBool, value) + } + if value, ok := _u.mutation.LedgerTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString, value) + } + if _u.mutation.LedgerTransactionGroupIDCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedruninvoicedusage.FieldAnnotations, field.TypeJSON) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesInclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.TaxesExclusiveTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.ChargesTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldChargesTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.DiscountsTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldDiscountsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.CreditsTotal(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldCreditsTotal, field.TypeOther, value) + } + if value, ok := _u.mutation.Total(); ok { + _spec.SetField(chargeusagebasedruninvoicedusage.FieldTotal, field.TypeOther, value) + } + _node = &ChargeUsageBasedRunInvoicedUsage{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedruninvoicedusage.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/openmeter/ent/db/chargeusagebasedrunpayment.go b/openmeter/ent/db/chargeusagebasedrunpayment.go new file mode 100644 index 0000000000..063210cade --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment.go @@ -0,0 +1,312 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunPayment is the model entity for the ChargeUsageBasedRunPayment schema. +type ChargeUsageBasedRunPayment struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // LineID holds the value of the "line_id" field. + LineID string `json:"line_id,omitempty"` + // ServicePeriodFrom holds the value of the "service_period_from" field. + ServicePeriodFrom time.Time `json:"service_period_from,omitempty"` + // ServicePeriodTo holds the value of the "service_period_to" field. + ServicePeriodTo time.Time `json:"service_period_to,omitempty"` + // Status holds the value of the "status" field. + Status payment.Status `json:"status,omitempty"` + // Amount holds the value of the "amount" field. + Amount alpacadecimal.Decimal `json:"amount,omitempty"` + // AuthorizedTransactionGroupID holds the value of the "authorized_transaction_group_id" field. + AuthorizedTransactionGroupID *string `json:"authorized_transaction_group_id,omitempty"` + // AuthorizedAt holds the value of the "authorized_at" field. + AuthorizedAt *time.Time `json:"authorized_at,omitempty"` + // SettledTransactionGroupID holds the value of the "settled_transaction_group_id" field. + SettledTransactionGroupID *string `json:"settled_transaction_group_id,omitempty"` + // SettledAt holds the value of the "settled_at" field. + SettledAt *time.Time `json:"settled_at,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + // Annotations holds the value of the "annotations" field. + Annotations models.Annotations `json:"annotations,omitempty"` + // RunID holds the value of the "run_id" field. + RunID string `json:"run_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedRunPaymentQuery when eager-loading is set. + Edges ChargeUsageBasedRunPaymentEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedRunPaymentEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedRunPaymentEdges struct { + // Run holds the value of the run edge. + Run *ChargeUsageBasedRuns `json:"run,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// RunOrErr returns the Run value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunPaymentEdges) RunOrErr() (*ChargeUsageBasedRuns, error) { + if e.Run != nil { + return e.Run, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeusagebasedruns.Label} + } + return nil, &NotLoadedError{edge: "run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBasedRunPayment) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebasedrunpayment.FieldAnnotations: + values[i] = new([]byte) + case chargeusagebasedrunpayment.FieldAmount: + values[i] = new(alpacadecimal.Decimal) + case chargeusagebasedrunpayment.FieldID, chargeusagebasedrunpayment.FieldLineID, chargeusagebasedrunpayment.FieldStatus, chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, chargeusagebasedrunpayment.FieldSettledTransactionGroupID, chargeusagebasedrunpayment.FieldNamespace, chargeusagebasedrunpayment.FieldRunID: + values[i] = new(sql.NullString) + case chargeusagebasedrunpayment.FieldServicePeriodFrom, chargeusagebasedrunpayment.FieldServicePeriodTo, chargeusagebasedrunpayment.FieldAuthorizedAt, chargeusagebasedrunpayment.FieldSettledAt, chargeusagebasedrunpayment.FieldCreatedAt, chargeusagebasedrunpayment.FieldUpdatedAt, chargeusagebasedrunpayment.FieldDeletedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeUsageBasedRunPayment fields. +func (_m *ChargeUsageBasedRunPayment) 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) + } + for i := range columns { + switch columns[i] { + case chargeusagebasedrunpayment.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case chargeusagebasedrunpayment.FieldLineID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field line_id", values[i]) + } else if value.Valid { + _m.LineID = value.String + } + case chargeusagebasedrunpayment.FieldServicePeriodFrom: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_from", values[i]) + } else if value.Valid { + _m.ServicePeriodFrom = value.Time + } + case chargeusagebasedrunpayment.FieldServicePeriodTo: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field service_period_to", values[i]) + } else if value.Valid { + _m.ServicePeriodTo = value.Time + } + case chargeusagebasedrunpayment.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + _m.Status = payment.Status(value.String) + } + case chargeusagebasedrunpayment.FieldAmount: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount", values[i]) + } else if value != nil { + _m.Amount = *value + } + case chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field authorized_transaction_group_id", values[i]) + } else if value.Valid { + _m.AuthorizedTransactionGroupID = new(string) + *_m.AuthorizedTransactionGroupID = value.String + } + case chargeusagebasedrunpayment.FieldAuthorizedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field authorized_at", values[i]) + } else if value.Valid { + _m.AuthorizedAt = new(time.Time) + *_m.AuthorizedAt = value.Time + } + case chargeusagebasedrunpayment.FieldSettledTransactionGroupID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field settled_transaction_group_id", values[i]) + } else if value.Valid { + _m.SettledTransactionGroupID = new(string) + *_m.SettledTransactionGroupID = value.String + } + case chargeusagebasedrunpayment.FieldSettledAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field settled_at", values[i]) + } else if value.Valid { + _m.SettledAt = new(time.Time) + *_m.SettledAt = value.Time + } + case chargeusagebasedrunpayment.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + _m.Namespace = value.String + } + case chargeusagebasedrunpayment.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case chargeusagebasedrunpayment.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case chargeusagebasedrunpayment.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = new(time.Time) + *_m.DeletedAt = value.Time + } + case chargeusagebasedrunpayment.FieldAnnotations: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field annotations", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Annotations); err != nil { + return fmt.Errorf("unmarshal field annotations: %w", err) + } + } + case chargeusagebasedrunpayment.FieldRunID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field run_id", values[i]) + } else if value.Valid { + _m.RunID = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeUsageBasedRunPayment. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBasedRunPayment) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRun queries the "run" edge of the ChargeUsageBasedRunPayment entity. +func (_m *ChargeUsageBasedRunPayment) QueryRun() *ChargeUsageBasedRunsQuery { + return NewChargeUsageBasedRunPaymentClient(_m.config).QueryRun(_m) +} + +// Update returns a builder for updating this ChargeUsageBasedRunPayment. +// Note that you need to call ChargeUsageBasedRunPayment.Unwrap() before calling this method if this ChargeUsageBasedRunPayment +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBasedRunPayment) Update() *ChargeUsageBasedRunPaymentUpdateOne { + return NewChargeUsageBasedRunPaymentClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBasedRunPayment 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 (_m *ChargeUsageBasedRunPayment) Unwrap() *ChargeUsageBasedRunPayment { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBasedRunPayment is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBasedRunPayment) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBasedRunPayment(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("line_id=") + builder.WriteString(_m.LineID) + builder.WriteString(", ") + builder.WriteString("service_period_from=") + builder.WriteString(_m.ServicePeriodFrom.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("service_period_to=") + builder.WriteString(_m.ServicePeriodTo.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + if v := _m.AuthorizedTransactionGroupID; v != nil { + builder.WriteString("authorized_transaction_group_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.AuthorizedAt; v != nil { + builder.WriteString("authorized_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.SettledTransactionGroupID; v != nil { + builder.WriteString("settled_transaction_group_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SettledAt; v != nil { + builder.WriteString("settled_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("annotations=") + builder.WriteString(fmt.Sprintf("%v", _m.Annotations)) + builder.WriteString(", ") + builder.WriteString("run_id=") + builder.WriteString(_m.RunID) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunPayments is a parsable slice of ChargeUsageBasedRunPayment. +type ChargeUsageBasedRunPayments []*ChargeUsageBasedRunPayment diff --git a/openmeter/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go b/openmeter/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go new file mode 100644 index 0000000000..ebeaa37141 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go @@ -0,0 +1,209 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedrunpayment + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" +) + +const ( + // Label holds the string label denoting the chargeusagebasedrunpayment type in the database. + Label = "charge_usage_based_run_payment" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldLineID holds the string denoting the line_id field in the database. + FieldLineID = "line_id" + // FieldServicePeriodFrom holds the string denoting the service_period_from field in the database. + FieldServicePeriodFrom = "service_period_from" + // FieldServicePeriodTo holds the string denoting the service_period_to field in the database. + FieldServicePeriodTo = "service_period_to" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldAuthorizedTransactionGroupID holds the string denoting the authorized_transaction_group_id field in the database. + FieldAuthorizedTransactionGroupID = "authorized_transaction_group_id" + // FieldAuthorizedAt holds the string denoting the authorized_at field in the database. + FieldAuthorizedAt = "authorized_at" + // FieldSettledTransactionGroupID holds the string denoting the settled_transaction_group_id field in the database. + FieldSettledTransactionGroupID = "settled_transaction_group_id" + // FieldSettledAt holds the string denoting the settled_at field in the database. + FieldSettledAt = "settled_at" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldAnnotations holds the string denoting the annotations field in the database. + FieldAnnotations = "annotations" + // FieldRunID holds the string denoting the run_id field in the database. + FieldRunID = "run_id" + // EdgeRun holds the string denoting the run edge name in mutations. + EdgeRun = "run" + // Table holds the table name of the chargeusagebasedrunpayment in the database. + Table = "charge_usage_based_run_payments" + // RunTable is the table that holds the run relation/edge. + RunTable = "charge_usage_based_run_payments" + // RunInverseTable is the table name for the ChargeUsageBasedRuns entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruns" package. + RunInverseTable = "charge_usage_based_runs" + // RunColumn is the table column denoting the run relation/edge. + RunColumn = "run_id" +) + +// Columns holds all SQL columns for chargeusagebasedrunpayment fields. +var Columns = []string{ + FieldID, + FieldLineID, + FieldServicePeriodFrom, + FieldServicePeriodTo, + FieldStatus, + FieldAmount, + FieldAuthorizedTransactionGroupID, + FieldAuthorizedAt, + FieldSettledTransactionGroupID, + FieldSettledAt, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldAnnotations, + FieldRunID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // AuthorizedTransactionGroupIDValidator is a validator for the "authorized_transaction_group_id" field. It is called by the builders before save. + AuthorizedTransactionGroupIDValidator func(string) error + // SettledTransactionGroupIDValidator is a validator for the "settled_transaction_group_id" field. It is called by the builders before save. + SettledTransactionGroupIDValidator func(string) error + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s payment.Status) error { + switch s { + case "authorized", "settled": + return nil + default: + return fmt.Errorf("chargeusagebasedrunpayment: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the ChargeUsageBasedRunPayment 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() +} + +// ByLineID orders the results by the line_id field. +func ByLineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLineID, opts...).ToFunc() +} + +// ByServicePeriodFrom orders the results by the service_period_from field. +func ByServicePeriodFrom(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodFrom, opts...).ToFunc() +} + +// ByServicePeriodTo orders the results by the service_period_to field. +func ByServicePeriodTo(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldServicePeriodTo, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByAuthorizedTransactionGroupID orders the results by the authorized_transaction_group_id field. +func ByAuthorizedTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorizedTransactionGroupID, opts...).ToFunc() +} + +// ByAuthorizedAt orders the results by the authorized_at field. +func ByAuthorizedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorizedAt, opts...).ToFunc() +} + +// BySettledTransactionGroupID orders the results by the settled_transaction_group_id field. +func BySettledTransactionGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSettledTransactionGroupID, opts...).ToFunc() +} + +// BySettledAt orders the results by the settled_at field. +func BySettledAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSettledAt, opts...).ToFunc() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByRunID orders the results by the run_id field. +func ByRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRunID, opts...).ToFunc() +} + +// ByRunField orders the results by run field. +func ByRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRunStep(), sql.OrderByField(field, opts...)) + } +} +func newRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, RunTable, RunColumn), + ) +} diff --git a/openmeter/ent/db/chargeusagebasedrunpayment/where.go b/openmeter/ent/db/chargeusagebasedrunpayment/where.go new file mode 100644 index 0000000000..b07c94ebbd --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment/where.go @@ -0,0 +1,906 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedrunpayment + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldID, id)) +} + +// LineID applies equality check predicate on the "line_id" field. It's identical to LineIDEQ. +func LineID(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldLineID, v)) +} + +// ServicePeriodFrom applies equality check predicate on the "service_period_from" field. It's identical to ServicePeriodFromEQ. +func ServicePeriodFrom(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodTo applies equality check predicate on the "service_period_to" field. It's identical to ServicePeriodToEQ. +func ServicePeriodTo(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldAmount, v)) +} + +// AuthorizedTransactionGroupID applies equality check predicate on the "authorized_transaction_group_id" field. It's identical to AuthorizedTransactionGroupIDEQ. +func AuthorizedTransactionGroupID(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedAt applies equality check predicate on the "authorized_at" field. It's identical to AuthorizedAtEQ. +func AuthorizedAt(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldAuthorizedAt, v)) +} + +// SettledTransactionGroupID applies equality check predicate on the "settled_transaction_group_id" field. It's identical to SettledTransactionGroupIDEQ. +func SettledTransactionGroupID(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledAt applies equality check predicate on the "settled_at" field. It's identical to SettledAtEQ. +func SettledAt(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldNamespace, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// RunID applies equality check predicate on the "run_id" field. It's identical to RunIDEQ. +func RunID(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldRunID, v)) +} + +// LineIDEQ applies the EQ predicate on the "line_id" field. +func LineIDEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldLineID, v)) +} + +// LineIDNEQ applies the NEQ predicate on the "line_id" field. +func LineIDNEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldLineID, v)) +} + +// LineIDIn applies the In predicate on the "line_id" field. +func LineIDIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldLineID, vs...)) +} + +// LineIDNotIn applies the NotIn predicate on the "line_id" field. +func LineIDNotIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldLineID, vs...)) +} + +// LineIDGT applies the GT predicate on the "line_id" field. +func LineIDGT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldLineID, v)) +} + +// LineIDGTE applies the GTE predicate on the "line_id" field. +func LineIDGTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldLineID, v)) +} + +// LineIDLT applies the LT predicate on the "line_id" field. +func LineIDLT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldLineID, v)) +} + +// LineIDLTE applies the LTE predicate on the "line_id" field. +func LineIDLTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldLineID, v)) +} + +// LineIDContains applies the Contains predicate on the "line_id" field. +func LineIDContains(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContains(FieldLineID, v)) +} + +// LineIDHasPrefix applies the HasPrefix predicate on the "line_id" field. +func LineIDHasPrefix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasPrefix(FieldLineID, v)) +} + +// LineIDHasSuffix applies the HasSuffix predicate on the "line_id" field. +func LineIDHasSuffix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasSuffix(FieldLineID, v)) +} + +// LineIDEqualFold applies the EqualFold predicate on the "line_id" field. +func LineIDEqualFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldLineID, v)) +} + +// LineIDContainsFold applies the ContainsFold predicate on the "line_id" field. +func LineIDContainsFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldLineID, v)) +} + +// ServicePeriodFromEQ applies the EQ predicate on the "service_period_from" field. +func ServicePeriodFromEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromNEQ applies the NEQ predicate on the "service_period_from" field. +func ServicePeriodFromNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromIn applies the In predicate on the "service_period_from" field. +func ServicePeriodFromIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromNotIn applies the NotIn predicate on the "service_period_from" field. +func ServicePeriodFromNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldServicePeriodFrom, vs...)) +} + +// ServicePeriodFromGT applies the GT predicate on the "service_period_from" field. +func ServicePeriodFromGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromGTE applies the GTE predicate on the "service_period_from" field. +func ServicePeriodFromGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLT applies the LT predicate on the "service_period_from" field. +func ServicePeriodFromLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldServicePeriodFrom, v)) +} + +// ServicePeriodFromLTE applies the LTE predicate on the "service_period_from" field. +func ServicePeriodFromLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldServicePeriodFrom, v)) +} + +// ServicePeriodToEQ applies the EQ predicate on the "service_period_to" field. +func ServicePeriodToEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToNEQ applies the NEQ predicate on the "service_period_to" field. +func ServicePeriodToNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldServicePeriodTo, v)) +} + +// ServicePeriodToIn applies the In predicate on the "service_period_to" field. +func ServicePeriodToIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToNotIn applies the NotIn predicate on the "service_period_to" field. +func ServicePeriodToNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldServicePeriodTo, vs...)) +} + +// ServicePeriodToGT applies the GT predicate on the "service_period_to" field. +func ServicePeriodToGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToGTE applies the GTE predicate on the "service_period_to" field. +func ServicePeriodToGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLT applies the LT predicate on the "service_period_to" field. +func ServicePeriodToLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldServicePeriodTo, v)) +} + +// ServicePeriodToLTE applies the LTE predicate on the "service_period_to" field. +func ServicePeriodToLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldServicePeriodTo, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v payment.Status) predicate.ChargeUsageBasedRunPayment { + vc := v + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v payment.Status) predicate.ChargeUsageBasedRunPayment { + vc := v + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...payment.Status) predicate.ChargeUsageBasedRunPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...payment.Status) predicate.ChargeUsageBasedRunPayment { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldStatus, v...)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldAmount, v)) +} + +// AuthorizedTransactionGroupIDEQ applies the EQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDNEQ applies the NEQ predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIn applies the In predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDNotIn applies the NotIn predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldAuthorizedTransactionGroupID, vs...)) +} + +// AuthorizedTransactionGroupIDGT applies the GT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDGTE applies the GTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDGTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLT applies the LT predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDLTE applies the LTE predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDLTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContains applies the Contains predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContains(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContains(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasPrefix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasPrefix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDHasSuffix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasSuffix(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDIsNil applies the IsNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDIsNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIsNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDNotNil applies the NotNil predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDNotNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotNull(FieldAuthorizedTransactionGroupID)) +} + +// AuthorizedTransactionGroupIDEqualFold applies the EqualFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDEqualFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedTransactionGroupIDContainsFold applies the ContainsFold predicate on the "authorized_transaction_group_id" field. +func AuthorizedTransactionGroupIDContainsFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldAuthorizedTransactionGroupID, v)) +} + +// AuthorizedAtEQ applies the EQ predicate on the "authorized_at" field. +func AuthorizedAtEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtNEQ applies the NEQ predicate on the "authorized_at" field. +func AuthorizedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIn applies the In predicate on the "authorized_at" field. +func AuthorizedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtNotIn applies the NotIn predicate on the "authorized_at" field. +func AuthorizedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldAuthorizedAt, vs...)) +} + +// AuthorizedAtGT applies the GT predicate on the "authorized_at" field. +func AuthorizedAtGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtGTE applies the GTE predicate on the "authorized_at" field. +func AuthorizedAtGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLT applies the LT predicate on the "authorized_at" field. +func AuthorizedAtLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldAuthorizedAt, v)) +} + +// AuthorizedAtLTE applies the LTE predicate on the "authorized_at" field. +func AuthorizedAtLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldAuthorizedAt, v)) +} + +// AuthorizedAtIsNil applies the IsNil predicate on the "authorized_at" field. +func AuthorizedAtIsNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIsNull(FieldAuthorizedAt)) +} + +// AuthorizedAtNotNil applies the NotNil predicate on the "authorized_at" field. +func AuthorizedAtNotNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotNull(FieldAuthorizedAt)) +} + +// SettledTransactionGroupIDEQ applies the EQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDNEQ applies the NEQ predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIn applies the In predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDNotIn applies the NotIn predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldSettledTransactionGroupID, vs...)) +} + +// SettledTransactionGroupIDGT applies the GT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDGTE applies the GTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDGTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLT applies the LT predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDLTE applies the LTE predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDLTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContains applies the Contains predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContains(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContains(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasPrefix applies the HasPrefix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasPrefix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasPrefix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDHasSuffix applies the HasSuffix predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDHasSuffix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasSuffix(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDIsNil applies the IsNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDIsNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIsNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDNotNil applies the NotNil predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDNotNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotNull(FieldSettledTransactionGroupID)) +} + +// SettledTransactionGroupIDEqualFold applies the EqualFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDEqualFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldSettledTransactionGroupID, v)) +} + +// SettledTransactionGroupIDContainsFold applies the ContainsFold predicate on the "settled_transaction_group_id" field. +func SettledTransactionGroupIDContainsFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldSettledTransactionGroupID, v)) +} + +// SettledAtEQ applies the EQ predicate on the "settled_at" field. +func SettledAtEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldSettledAt, v)) +} + +// SettledAtNEQ applies the NEQ predicate on the "settled_at" field. +func SettledAtNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldSettledAt, v)) +} + +// SettledAtIn applies the In predicate on the "settled_at" field. +func SettledAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldSettledAt, vs...)) +} + +// SettledAtNotIn applies the NotIn predicate on the "settled_at" field. +func SettledAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldSettledAt, vs...)) +} + +// SettledAtGT applies the GT predicate on the "settled_at" field. +func SettledAtGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldSettledAt, v)) +} + +// SettledAtGTE applies the GTE predicate on the "settled_at" field. +func SettledAtGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldSettledAt, v)) +} + +// SettledAtLT applies the LT predicate on the "settled_at" field. +func SettledAtLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldSettledAt, v)) +} + +// SettledAtLTE applies the LTE predicate on the "settled_at" field. +func SettledAtLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldSettledAt, v)) +} + +// SettledAtIsNil applies the IsNil predicate on the "settled_at" field. +func SettledAtIsNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIsNull(FieldSettledAt)) +} + +// SettledAtNotNil applies the NotNil predicate on the "settled_at" field. +func SettledAtNotNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotNull(FieldSettledAt)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotNull(FieldDeletedAt)) +} + +// AnnotationsIsNil applies the IsNil predicate on the "annotations" field. +func AnnotationsIsNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIsNull(FieldAnnotations)) +} + +// AnnotationsNotNil applies the NotNil predicate on the "annotations" field. +func AnnotationsNotNil() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotNull(FieldAnnotations)) +} + +// RunIDEQ applies the EQ predicate on the "run_id" field. +func RunIDEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEQ(FieldRunID, v)) +} + +// RunIDNEQ applies the NEQ predicate on the "run_id" field. +func RunIDNEQ(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNEQ(FieldRunID, v)) +} + +// RunIDIn applies the In predicate on the "run_id" field. +func RunIDIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldIn(FieldRunID, vs...)) +} + +// RunIDNotIn applies the NotIn predicate on the "run_id" field. +func RunIDNotIn(vs ...string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldNotIn(FieldRunID, vs...)) +} + +// RunIDGT applies the GT predicate on the "run_id" field. +func RunIDGT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGT(FieldRunID, v)) +} + +// RunIDGTE applies the GTE predicate on the "run_id" field. +func RunIDGTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldGTE(FieldRunID, v)) +} + +// RunIDLT applies the LT predicate on the "run_id" field. +func RunIDLT(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLT(FieldRunID, v)) +} + +// RunIDLTE applies the LTE predicate on the "run_id" field. +func RunIDLTE(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldLTE(FieldRunID, v)) +} + +// RunIDContains applies the Contains predicate on the "run_id" field. +func RunIDContains(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContains(FieldRunID, v)) +} + +// RunIDHasPrefix applies the HasPrefix predicate on the "run_id" field. +func RunIDHasPrefix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasPrefix(FieldRunID, v)) +} + +// RunIDHasSuffix applies the HasSuffix predicate on the "run_id" field. +func RunIDHasSuffix(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldHasSuffix(FieldRunID, v)) +} + +// RunIDEqualFold applies the EqualFold predicate on the "run_id" field. +func RunIDEqualFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldEqualFold(FieldRunID, v)) +} + +// RunIDContainsFold applies the ContainsFold predicate on the "run_id" field. +func RunIDContainsFold(v string) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.FieldContainsFold(FieldRunID, v)) +} + +// HasRun applies the HasEdge predicate on the "run" edge. +func HasRun() predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, RunTable, RunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRunWith applies the HasEdge predicate on the "run" edge with a given conditions (other predicates). +func HasRunWith(preds ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(func(s *sql.Selector) { + step := newRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ChargeUsageBasedRunPayment) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBasedRunPayment) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBasedRunPayment) predicate.ChargeUsageBasedRunPayment { + return predicate.ChargeUsageBasedRunPayment(sql.NotPredicates(p)) +} diff --git a/openmeter/ent/db/chargeusagebasedrunpayment_create.go b/openmeter/ent/db/chargeusagebasedrunpayment_create.go new file mode 100644 index 0000000000..e2a4696acb --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment_create.go @@ -0,0 +1,1325 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunPaymentCreate is the builder for creating a ChargeUsageBasedRunPayment entity. +type ChargeUsageBasedRunPaymentCreate struct { + config + mutation *ChargeUsageBasedRunPaymentMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetLineID sets the "line_id" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetLineID(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetLineID(v) + return _c +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetServicePeriodFrom(v) + return _c +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetServicePeriodTo(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetStatus(v payment.Status) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetAuthorizedTransactionGroupID(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetAuthorizedTransactionGroupID(v) + return _c +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetAuthorizedTransactionGroupID(*v) + } + return _c +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetAuthorizedAt(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetAuthorizedAt(v) + return _c +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableAuthorizedAt(v *time.Time) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetAuthorizedAt(*v) + } + return _c +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetSettledTransactionGroupID(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetSettledTransactionGroupID(v) + return _c +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableSettledTransactionGroupID(v *string) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetSettledTransactionGroupID(*v) + } + return _c +} + +// SetSettledAt sets the "settled_at" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetSettledAt(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetSettledAt(v) + return _c +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableSettledAt(v *time.Time) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetSettledAt(*v) + } + return _c +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNamespace(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetCreatedAt(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableCreatedAt(v *time.Time) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableUpdatedAt(v *time.Time) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetAnnotations sets the "annotations" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetAnnotations(v) + return _c +} + +// SetRunID sets the "run_id" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetRunID(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetRunID(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedRunPaymentCreate) SetID(v string) *ChargeUsageBasedRunPaymentCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunPaymentCreate) SetNillableID(v *string) *ChargeUsageBasedRunPaymentCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRun sets the "run" edge to the ChargeUsageBasedRuns entity. +func (_c *ChargeUsageBasedRunPaymentCreate) SetRun(v *ChargeUsageBasedRuns) *ChargeUsageBasedRunPaymentCreate { + return _c.SetRunID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunPaymentMutation object of the builder. +func (_c *ChargeUsageBasedRunPaymentCreate) Mutation() *ChargeUsageBasedRunPaymentMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBasedRunPayment in the database. +func (_c *ChargeUsageBasedRunPaymentCreate) Save(ctx context.Context) (*ChargeUsageBasedRunPayment, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedRunPaymentCreate) SaveX(ctx context.Context) *ChargeUsageBasedRunPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunPaymentCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunPaymentCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ChargeUsageBasedRunPaymentCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeusagebasedrunpayment.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeusagebasedrunpayment.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebasedrunpayment.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedRunPaymentCreate) check() error { + if _, ok := _c.mutation.LineID(); !ok { + return &ValidationError{Name: "line_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.line_id"`)} + } + if _, ok := _c.mutation.ServicePeriodFrom(); !ok { + return &ValidationError{Name: "service_period_from", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.service_period_from"`)} + } + if _, ok := _c.mutation.ServicePeriodTo(); !ok { + return &ValidationError{Name: "service_period_to", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.service_period_to"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := chargeusagebasedrunpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.status": %w`, err)} + } + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.amount"`)} + } + if v, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargeusagebasedrunpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _c.mutation.SettledTransactionGroupID(); ok { + if err := chargeusagebasedrunpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.settled_transaction_group_id": %w`, err)} + } + } + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebasedrunpayment.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.updated_at"`)} + } + if _, ok := _c.mutation.RunID(); !ok { + return &ValidationError{Name: "run_id", err: errors.New(`db: missing required field "ChargeUsageBasedRunPayment.run_id"`)} + } + if len(_c.mutation.RunIDs()) == 0 { + return &ValidationError{Name: "run", err: errors.New(`db: missing required edge "ChargeUsageBasedRunPayment.run"`)} + } + return nil +} + +func (_c *ChargeUsageBasedRunPaymentCreate) sqlSave(ctx context.Context) (*ChargeUsageBasedRunPayment, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected ChargeUsageBasedRunPayment.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedRunPaymentCreate) createSpec() (*ChargeUsageBasedRunPayment, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeUsageBasedRunPayment{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebasedrunpayment.Table, sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.LineID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldLineID, field.TypeString, value) + _node.LineID = value + } + if value, ok := _c.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldServicePeriodFrom, field.TypeTime, value) + _node.ServicePeriodFrom = value + } + if value, ok := _c.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldServicePeriodTo, field.TypeTime, value) + _node.ServicePeriodTo = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + _node.AuthorizedTransactionGroupID = &value + } + if value, ok := _c.mutation.AuthorizedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAuthorizedAt, field.TypeTime, value) + _node.AuthorizedAt = &value + } + if value, ok := _c.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldSettledTransactionGroupID, field.TypeString, value) + _node.SettledTransactionGroupID = &value + } + if value, ok := _c.mutation.SettledAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldSettledAt, field.TypeTime, value) + _node.SettledAt = &value + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAnnotations, field.TypeJSON, value) + _node.Annotations = value + } + if nodes := _c.mutation.RunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: chargeusagebasedrunpayment.RunTable, + Columns: []string{chargeusagebasedrunpayment.RunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RunID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRunPayment.Create(). +// SetLineID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunPaymentUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunPaymentCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunPaymentUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedRunPaymentUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunPaymentCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedRunPaymentUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunPaymentUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedRunPaymentUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBasedRunPayment node. + ChargeUsageBasedRunPaymentUpsertOne struct { + create *ChargeUsageBasedRunPaymentCreate + } + + // ChargeUsageBasedRunPaymentUpsert is the "OnConflict" setter. + ChargeUsageBasedRunPaymentUpsert struct { + *sql.UpdateSet + } +) + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldServicePeriodFrom, v) + return u +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateServicePeriodFrom() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldServicePeriodFrom) + return u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldServicePeriodTo, v) + return u +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateServicePeriodTo() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldServicePeriodTo) + return u +} + +// SetStatus sets the "status" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetStatus(v payment.Status) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateStatus() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldStatus) + return u +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldAmount, v) + return u +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateAmount() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldAmount) + return u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetAuthorizedTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, v) + return u +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsert) ClearAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpsert { + u.SetNull(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID) + return u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetAuthorizedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldAuthorizedAt, v) + return u +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateAuthorizedAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldAuthorizedAt) + return u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) ClearAuthorizedAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetNull(chargeusagebasedrunpayment.FieldAuthorizedAt) + return u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetSettledTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldSettledTransactionGroupID, v) + return u +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldSettledTransactionGroupID) + return u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsert) ClearSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpsert { + u.SetNull(chargeusagebasedrunpayment.FieldSettledTransactionGroupID) + return u +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetSettledAt(v time.Time) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldSettledAt, v) + return u +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateSettledAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldSettledAt) + return u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) ClearSettledAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetNull(chargeusagebasedrunpayment.FieldSettledAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateUpdatedAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetDeletedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateDeletedAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunPaymentUpsert) ClearDeletedAt() *ChargeUsageBasedRunPaymentUpsert { + u.SetNull(chargeusagebasedrunpayment.FieldDeletedAt) + return u +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunPaymentUpsert) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunPaymentUpsert { + u.Set(chargeusagebasedrunpayment.FieldAnnotations, v) + return u +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsert) UpdateAnnotations() *ChargeUsageBasedRunPaymentUpsert { + u.SetExcluded(chargeusagebasedrunpayment.FieldAnnotations) + return u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunPaymentUpsert) ClearAnnotations() *ChargeUsageBasedRunPaymentUpsert { + u.SetNull(chargeusagebasedrunpayment.FieldAnnotations) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedrunpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateNewValues() *ChargeUsageBasedRunPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldID) + } + if _, exists := u.create.mutation.LineID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldLineID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldCreatedAt) + } + if _, exists := u.create.mutation.RunID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldRunID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunPaymentUpsertOne) Ignore() *ChargeUsageBasedRunPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunPaymentUpsertOne) DoNothing() *ChargeUsageBasedRunPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunPaymentCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunPaymentUpsertOne) Update(set func(*ChargeUsageBasedRunPaymentUpsert)) *ChargeUsageBasedRunPaymentUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateServicePeriodFrom() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateServicePeriodTo() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetStatus(v payment.Status) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateStatus() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateAmount() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetAuthorizedTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ClearAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetAuthorizedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateAuthorizedAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ClearAuthorizedAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetSettledTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ClearSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetSettledAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateSettledAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ClearSettledAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateUpdatedAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateDeletedAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ClearDeletedAt() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertOne) UpdateAnnotations() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ClearAnnotations() *ChargeUsageBasedRunPaymentUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunPaymentUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunPaymentCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ChargeUsageBasedRunPaymentUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: ChargeUsageBasedRunPaymentUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedRunPaymentUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ChargeUsageBasedRunPaymentUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedRunPaymentCreateBulk is the builder for creating many ChargeUsageBasedRunPayment entities in bulk. +type ChargeUsageBasedRunPaymentCreateBulk struct { + config + err error + builders []*ChargeUsageBasedRunPaymentCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBasedRunPayment entities in the database. +func (_c *ChargeUsageBasedRunPaymentCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBasedRunPayment, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBasedRunPayment, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ChargeUsageBasedRunPaymentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ChargeUsageBasedRunPaymentCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBasedRunPayment { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunPaymentCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunPaymentCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRunPayment.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunPaymentUpsert) { +// SetLineID(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunPaymentCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunPaymentUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedRunPaymentUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunPayment.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunPaymentCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedRunPaymentUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunPaymentUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedRunPaymentUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBasedRunPayment nodes. +type ChargeUsageBasedRunPaymentUpsertBulk struct { + create *ChargeUsageBasedRunPaymentCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunPayment.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedrunpayment.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateNewValues() *ChargeUsageBasedRunPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldID) + } + if _, exists := b.mutation.LineID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldLineID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldCreatedAt) + } + if _, exists := b.mutation.RunID(); exists { + s.SetIgnore(chargeusagebasedrunpayment.FieldRunID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRunPayment.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunPaymentUpsertBulk) Ignore() *ChargeUsageBasedRunPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) DoNothing() *ChargeUsageBasedRunPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunPaymentCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) Update(set func(*ChargeUsageBasedRunPaymentUpsert)) *ChargeUsageBasedRunPaymentUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunPaymentUpsert{UpdateSet: update}) + })) + return u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetServicePeriodFrom(v) + }) +} + +// UpdateServicePeriodFrom sets the "service_period_from" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateServicePeriodFrom() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateServicePeriodFrom() + }) +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetServicePeriodTo(v) + }) +} + +// UpdateServicePeriodTo sets the "service_period_to" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateServicePeriodTo() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateServicePeriodTo() + }) +} + +// SetStatus sets the "status" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetStatus(v payment.Status) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateStatus() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateStatus() + }) +} + +// SetAmount sets the "amount" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAmount(v) + }) +} + +// UpdateAmount sets the "amount" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateAmount() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAmount() + }) +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetAuthorizedTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAuthorizedTransactionGroupID(v) + }) +} + +// UpdateAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAuthorizedTransactionGroupID() + }) +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ClearAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearAuthorizedTransactionGroupID() + }) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetAuthorizedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAuthorizedAt(v) + }) +} + +// UpdateAuthorizedAt sets the "authorized_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateAuthorizedAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAuthorizedAt() + }) +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ClearAuthorizedAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearAuthorizedAt() + }) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetSettledTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetSettledTransactionGroupID(v) + }) +} + +// UpdateSettledTransactionGroupID sets the "settled_transaction_group_id" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateSettledTransactionGroupID() + }) +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ClearSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearSettledTransactionGroupID() + }) +} + +// SetSettledAt sets the "settled_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetSettledAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetSettledAt(v) + }) +} + +// UpdateSettledAt sets the "settled_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateSettledAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateSettledAt() + }) +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ClearSettledAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearSettledAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateUpdatedAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetDeletedAt(v time.Time) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateDeletedAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ClearDeletedAt() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAnnotations sets the "annotations" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.SetAnnotations(v) + }) +} + +// UpdateAnnotations sets the "annotations" field to the value that was provided on create. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) UpdateAnnotations() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.UpdateAnnotations() + }) +} + +// ClearAnnotations clears the value of the "annotations" field. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ClearAnnotations() *ChargeUsageBasedRunPaymentUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunPaymentUpsert) { + s.ClearAnnotations() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ChargeUsageBasedRunPaymentCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunPaymentCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunPaymentUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedrunpayment_delete.go b/openmeter/ent/db/chargeusagebasedrunpayment_delete.go new file mode 100644 index 0000000000..4d3285ca8a --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunPaymentDelete is the builder for deleting a ChargeUsageBasedRunPayment entity. +type ChargeUsageBasedRunPaymentDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunPaymentMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunPaymentDelete builder. +func (_d *ChargeUsageBasedRunPaymentDelete) Where(ps ...predicate.ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedRunPaymentDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunPaymentDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedRunPaymentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebasedrunpayment.Table, sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ChargeUsageBasedRunPaymentDeleteOne is the builder for deleting a single ChargeUsageBasedRunPayment entity. +type ChargeUsageBasedRunPaymentDeleteOne struct { + _d *ChargeUsageBasedRunPaymentDelete +} + +// Where appends a list predicates to the ChargeUsageBasedRunPaymentDelete builder. +func (_d *ChargeUsageBasedRunPaymentDeleteOne) Where(ps ...predicate.ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedRunPaymentDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebasedrunpayment.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunPaymentDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedrunpayment_query.go b/openmeter/ent/db/chargeusagebasedrunpayment_query.go new file mode 100644 index 0000000000..4f781fccf5 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment_query.go @@ -0,0 +1,643 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunPaymentQuery is the builder for querying ChargeUsageBasedRunPayment entities. +type ChargeUsageBasedRunPaymentQuery struct { + config + ctx *QueryContext + order []chargeusagebasedrunpayment.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBasedRunPayment + withRun *ChargeUsageBasedRunsQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ChargeUsageBasedRunPaymentQuery builder. +func (_q *ChargeUsageBasedRunPaymentQuery) Where(ps ...predicate.ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedRunPaymentQuery) Limit(limit int) *ChargeUsageBasedRunPaymentQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedRunPaymentQuery) Offset(offset int) *ChargeUsageBasedRunPaymentQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ChargeUsageBasedRunPaymentQuery) Unique(unique bool) *ChargeUsageBasedRunPaymentQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedRunPaymentQuery) Order(o ...chargeusagebasedrunpayment.OrderOption) *ChargeUsageBasedRunPaymentQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRun chains the current query on the "run" edge. +func (_q *ChargeUsageBasedRunPaymentQuery) QueryRun() *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.FieldID, selector), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedrunpayment.RunTable, chargeusagebasedrunpayment.RunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBasedRunPayment entity from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunPayment was found. +func (_q *ChargeUsageBasedRunPaymentQuery) First(ctx context.Context) (*ChargeUsageBasedRunPayment, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{chargeusagebasedrunpayment.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) FirstX(ctx context.Context) *ChargeUsageBasedRunPayment { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBasedRunPayment ID from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRunPayment ID was found. +func (_q *ChargeUsageBasedRunPaymentQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{chargeusagebasedrunpayment.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBasedRunPayment entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunPayment entity is found. +// Returns a *NotFoundError when no ChargeUsageBasedRunPayment entities are found. +func (_q *ChargeUsageBasedRunPaymentQuery) Only(ctx context.Context) (*ChargeUsageBasedRunPayment, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{chargeusagebasedrunpayment.Label} + default: + return nil, &NotSingularError{chargeusagebasedrunpayment.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) OnlyX(ctx context.Context) *ChargeUsageBasedRunPayment { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBasedRunPayment ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBasedRunPayment ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedRunPaymentQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{chargeusagebasedrunpayment.Label} + default: + err = &NotSingularError{chargeusagebasedrunpayment.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ChargeUsageBasedRunPayments. +func (_q *ChargeUsageBasedRunPaymentQuery) All(ctx context.Context) ([]*ChargeUsageBasedRunPayment, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBasedRunPayment, *ChargeUsageBasedRunPaymentQuery]() + return withInterceptors[[]*ChargeUsageBasedRunPayment](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) AllX(ctx context.Context) []*ChargeUsageBasedRunPayment { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBasedRunPayment IDs. +func (_q *ChargeUsageBasedRunPaymentQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(chargeusagebasedrunpayment.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ChargeUsageBasedRunPaymentQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ChargeUsageBasedRunPaymentQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ChargeUsageBasedRunPaymentQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ChargeUsageBasedRunPaymentQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedRunPaymentQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ChargeUsageBasedRunPaymentQuery) Clone() *ChargeUsageBasedRunPaymentQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedRunPaymentQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebasedrunpayment.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBasedRunPayment{}, _q.predicates...), + withRun: _q.withRun.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithRun tells the query-builder to eager-load the nodes that are connected to +// the "run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunPaymentQuery) WithRun(opts ...func(*ChargeUsageBasedRunsQuery)) *ChargeUsageBasedRunPaymentQuery { + query := (&ChargeUsageBasedRunsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRun = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// LineID string `json:"line_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBasedRunPayment.Query(). +// GroupBy(chargeusagebasedrunpayment.FieldLineID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunPaymentQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedRunPaymentGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedRunPaymentGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebasedrunpayment.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// LineID string `json:"line_id,omitempty"` +// } +// +// client.ChargeUsageBasedRunPayment.Query(). +// Select(chargeusagebasedrunpayment.FieldLineID). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunPaymentQuery) Select(fields ...string) *ChargeUsageBasedRunPaymentSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedRunPaymentSelect{ChargeUsageBasedRunPaymentQuery: _q} + sbuild.label = chargeusagebasedrunpayment.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedRunPaymentSelect configured with the given aggregations. +func (_q *ChargeUsageBasedRunPaymentQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunPaymentSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedRunPaymentQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !chargeusagebasedrunpayment.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ChargeUsageBasedRunPaymentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBasedRunPayment, error) { + var ( + nodes = []*ChargeUsageBasedRunPayment{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBasedRunPayment).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBasedRunPayment{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withRun; query != nil { + if err := _q.loadRun(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRunPayment, e *ChargeUsageBasedRuns) { n.Edges.Run = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedRunPaymentQuery) loadRun(ctx context.Context, query *ChargeUsageBasedRunsQuery, nodes []*ChargeUsageBasedRunPayment, init func(*ChargeUsageBasedRunPayment), assign func(*ChargeUsageBasedRunPayment, *ChargeUsageBasedRuns)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRunPayment) + for i := range nodes { + fk := nodes[i].RunID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeusagebasedruns.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ChargeUsageBasedRunPaymentQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ChargeUsageBasedRunPaymentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.Columns, sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedrunpayment.FieldID) + for i := range fields { + if fields[i] != chargeusagebasedrunpayment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRun != nil { + _spec.Node.AddColumnOnce(chargeusagebasedrunpayment.FieldRunID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ChargeUsageBasedRunPaymentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebasedrunpayment.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebasedrunpayment.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *ChargeUsageBasedRunPaymentQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedRunPaymentQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *ChargeUsageBasedRunPaymentQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedRunPaymentQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedRunPaymentGroupBy is the group-by builder for ChargeUsageBasedRunPayment entities. +type ChargeUsageBasedRunPaymentGroupBy struct { + selector + build *ChargeUsageBasedRunPaymentQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedRunPaymentGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunPaymentGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedRunPaymentGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunPaymentQuery, *ChargeUsageBasedRunPaymentGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedRunPaymentGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedRunPaymentQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ChargeUsageBasedRunPaymentSelect is the builder for selecting fields of ChargeUsageBasedRunPayment entities. +type ChargeUsageBasedRunPaymentSelect struct { + *ChargeUsageBasedRunPaymentQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedRunPaymentSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunPaymentSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedRunPaymentSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunPaymentQuery, *ChargeUsageBasedRunPaymentSelect](ctx, _s.ChargeUsageBasedRunPaymentQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedRunPaymentSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedRunPaymentQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/openmeter/ent/db/chargeusagebasedrunpayment_update.go b/openmeter/ent/db/chargeusagebasedrunpayment_update.go new file mode 100644 index 0000000000..75b104c2e1 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedrunpayment_update.go @@ -0,0 +1,699 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" + "github.com/openmeterio/openmeter/pkg/models" +) + +// ChargeUsageBasedRunPaymentUpdate is the builder for updating ChargeUsageBasedRunPayment entities. +type ChargeUsageBasedRunPaymentUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunPaymentMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunPaymentUpdate builder. +func (_u *ChargeUsageBasedRunPaymentUpdate) Where(ps ...predicate.ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetStatus(v payment.Status) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableStatus(v *payment.Status) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetAuthorizedTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) ClearAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetAuthorizedAt(v time.Time) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableAuthorizedAt(v *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) ClearAuthorizedAt() *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetSettledTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableSettledTransactionGroupID(v *string) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) ClearSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetSettledAt(v time.Time) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableSettledAt(v *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) ClearSettledAt() *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) ClearDeletedAt() *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunPaymentUpdate) ClearAnnotations() *ChargeUsageBasedRunPaymentUpdate { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeUsageBasedRunPaymentMutation object of the builder. +func (_u *ChargeUsageBasedRunPaymentUpdate) Mutation() *ChargeUsageBasedRunPaymentMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedRunPaymentUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunPaymentUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedRunPaymentUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunPaymentUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunPaymentUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedrunpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunPaymentUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeusagebasedrunpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargeusagebasedrunpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargeusagebasedrunpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunPayment.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunPaymentUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.Columns, sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldAnnotations, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedrunpayment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedRunPaymentUpdateOne is the builder for updating a single ChargeUsageBasedRunPayment entity. +type ChargeUsageBasedRunPaymentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedRunPaymentMutation +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetServicePeriodFrom(v time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetServicePeriodFrom(v) + return _u +} + +// SetNillableServicePeriodFrom sets the "service_period_from" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableServicePeriodFrom(v *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodFrom(*v) + } + return _u +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetServicePeriodTo(v time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetServicePeriodTo(v) + return _u +} + +// SetNillableServicePeriodTo sets the "service_period_to" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableServicePeriodTo(v *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetServicePeriodTo(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetStatus(v payment.Status) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableStatus(v *payment.Status) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetAmount sets the "amount" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetAmount(v alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetAmount(v) + return _u +} + +// SetNillableAmount sets the "amount" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableAmount(v *alpacadecimal.Decimal) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetAmount(*v) + } + return _u +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetAuthorizedTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetAuthorizedTransactionGroupID(v) + return _u +} + +// SetNillableAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableAuthorizedTransactionGroupID(v *string) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedTransactionGroupID(*v) + } + return _u +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ClearAuthorizedTransactionGroupID() *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.ClearAuthorizedTransactionGroupID() + return _u +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetAuthorizedAt(v time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetAuthorizedAt(v) + return _u +} + +// SetNillableAuthorizedAt sets the "authorized_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableAuthorizedAt(v *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetAuthorizedAt(*v) + } + return _u +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ClearAuthorizedAt() *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.ClearAuthorizedAt() + return _u +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetSettledTransactionGroupID(v string) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetSettledTransactionGroupID(v) + return _u +} + +// SetNillableSettledTransactionGroupID sets the "settled_transaction_group_id" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableSettledTransactionGroupID(v *string) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetSettledTransactionGroupID(*v) + } + return _u +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ClearSettledTransactionGroupID() *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.ClearSettledTransactionGroupID() + return _u +} + +// SetSettledAt sets the "settled_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetSettledAt(v time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetSettledAt(v) + return _u +} + +// SetNillableSettledAt sets the "settled_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableSettledAt(v *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetSettledAt(*v) + } + return _u +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ClearSettledAt() *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.ClearSettledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ClearDeletedAt() *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAnnotations sets the "annotations" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SetAnnotations(v models.Annotations) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.SetAnnotations(v) + return _u +} + +// ClearAnnotations clears the value of the "annotations" field. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ClearAnnotations() *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.ClearAnnotations() + return _u +} + +// Mutation returns the ChargeUsageBasedRunPaymentMutation object of the builder. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) Mutation() *ChargeUsageBasedRunPaymentMutation { + return _u.mutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunPaymentUpdate builder. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) Where(ps ...predicate.ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedRunPaymentUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBasedRunPayment entity. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) Save(ctx context.Context) (*ChargeUsageBasedRunPayment, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) SaveX(ctx context.Context) *ChargeUsageBasedRunPayment { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedrunpayment.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunPaymentUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := chargeusagebasedrunpayment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.status": %w`, err)} + } + } + if v, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + if err := chargeusagebasedrunpayment.AuthorizedTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "authorized_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.authorized_transaction_group_id": %w`, err)} + } + } + if v, ok := _u.mutation.SettledTransactionGroupID(); ok { + if err := chargeusagebasedrunpayment.SettledTransactionGroupIDValidator(v); err != nil { + return &ValidationError{Name: "settled_transaction_group_id", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRunPayment.settled_transaction_group_id": %w`, err)} + } + } + if _u.mutation.RunCleared() && len(_u.mutation.RunIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRunPayment.run"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunPaymentUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBasedRunPayment, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.Columns, sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBasedRunPayment.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedrunpayment.FieldID) + for _, f := range fields { + if !chargeusagebasedrunpayment.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebasedrunpayment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ServicePeriodFrom(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldServicePeriodFrom, field.TypeTime, value) + } + if value, ok := _u.mutation.ServicePeriodTo(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldServicePeriodTo, field.TypeTime, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.Amount(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAmount, field.TypeOther, value) + } + if value, ok := _u.mutation.AuthorizedTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, field.TypeString, value) + } + if _u.mutation.AuthorizedTransactionGroupIDCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.AuthorizedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAuthorizedAt, field.TypeTime, value) + } + if _u.mutation.AuthorizedAtCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldAuthorizedAt, field.TypeTime) + } + if value, ok := _u.mutation.SettledTransactionGroupID(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldSettledTransactionGroupID, field.TypeString, value) + } + if _u.mutation.SettledTransactionGroupIDCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldSettledTransactionGroupID, field.TypeString) + } + if value, ok := _u.mutation.SettledAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldSettledAt, field.TypeTime, value) + } + if _u.mutation.SettledAtCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldSettledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Annotations(); ok { + _spec.SetField(chargeusagebasedrunpayment.FieldAnnotations, field.TypeJSON, value) + } + if _u.mutation.AnnotationsCleared() { + _spec.ClearField(chargeusagebasedrunpayment.FieldAnnotations, field.TypeJSON) + } + _node = &ChargeUsageBasedRunPayment{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedrunpayment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/openmeter/ent/db/chargeusagebasedruns.go b/openmeter/ent/db/chargeusagebasedruns.go new file mode 100644 index 0000000000..e590906459 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns.go @@ -0,0 +1,271 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" +) + +// ChargeUsageBasedRuns is the model entity for the ChargeUsageBasedRuns schema. +type ChargeUsageBasedRuns struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + // ChargeID holds the value of the "charge_id" field. + ChargeID string `json:"charge_id,omitempty"` + // Type holds the value of the "type" field. + Type usagebased.RealizationRunType `json:"type,omitempty"` + // Asof holds the value of the "asof" field. + Asof time.Time `json:"asof,omitempty"` + // MeterValue holds the value of the "meter_value" field. + MeterValue alpacadecimal.Decimal `json:"meter_value,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ChargeUsageBasedRunsQuery when eager-loading is set. + Edges ChargeUsageBasedRunsEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ChargeUsageBasedRunsEdges holds the relations/edges for other nodes in the graph. +type ChargeUsageBasedRunsEdges struct { + // UsageBased holds the value of the usage_based edge. + UsageBased *ChargeUsageBased `json:"usage_based,omitempty"` + // CreditAllocations holds the value of the credit_allocations edge. + CreditAllocations []*ChargeUsageBasedRunCreditAllocations `json:"credit_allocations,omitempty"` + // InvoicedUsage holds the value of the invoiced_usage edge. + InvoicedUsage *ChargeUsageBasedRunInvoicedUsage `json:"invoiced_usage,omitempty"` + // Payment holds the value of the payment edge. + Payment *ChargeUsageBasedRunPayment `json:"payment,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [4]bool +} + +// UsageBasedOrErr returns the UsageBased value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunsEdges) UsageBasedOrErr() (*ChargeUsageBased, error) { + if e.UsageBased != nil { + return e.UsageBased, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: chargeusagebased.Label} + } + return nil, &NotLoadedError{edge: "usage_based"} +} + +// CreditAllocationsOrErr returns the CreditAllocations value or an error if the edge +// was not loaded in eager-loading. +func (e ChargeUsageBasedRunsEdges) CreditAllocationsOrErr() ([]*ChargeUsageBasedRunCreditAllocations, error) { + if e.loadedTypes[1] { + return e.CreditAllocations, nil + } + return nil, &NotLoadedError{edge: "credit_allocations"} +} + +// InvoicedUsageOrErr returns the InvoicedUsage value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunsEdges) InvoicedUsageOrErr() (*ChargeUsageBasedRunInvoicedUsage, error) { + if e.InvoicedUsage != nil { + return e.InvoicedUsage, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: chargeusagebasedruninvoicedusage.Label} + } + return nil, &NotLoadedError{edge: "invoiced_usage"} +} + +// PaymentOrErr returns the Payment value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ChargeUsageBasedRunsEdges) PaymentOrErr() (*ChargeUsageBasedRunPayment, error) { + if e.Payment != nil { + return e.Payment, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: chargeusagebasedrunpayment.Label} + } + return nil, &NotLoadedError{edge: "payment"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ChargeUsageBasedRuns) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case chargeusagebasedruns.FieldMeterValue: + values[i] = new(alpacadecimal.Decimal) + case chargeusagebasedruns.FieldID, chargeusagebasedruns.FieldNamespace, chargeusagebasedruns.FieldChargeID, chargeusagebasedruns.FieldType: + values[i] = new(sql.NullString) + case chargeusagebasedruns.FieldCreatedAt, chargeusagebasedruns.FieldUpdatedAt, chargeusagebasedruns.FieldDeletedAt, chargeusagebasedruns.FieldAsof: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ChargeUsageBasedRuns fields. +func (_m *ChargeUsageBasedRuns) 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) + } + for i := range columns { + switch columns[i] { + case chargeusagebasedruns.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case chargeusagebasedruns.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + _m.Namespace = value.String + } + case chargeusagebasedruns.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case chargeusagebasedruns.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case chargeusagebasedruns.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = new(time.Time) + *_m.DeletedAt = value.Time + } + case chargeusagebasedruns.FieldChargeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field charge_id", values[i]) + } else if value.Valid { + _m.ChargeID = value.String + } + case chargeusagebasedruns.FieldType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + _m.Type = usagebased.RealizationRunType(value.String) + } + case chargeusagebasedruns.FieldAsof: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field asof", values[i]) + } else if value.Valid { + _m.Asof = value.Time + } + case chargeusagebasedruns.FieldMeterValue: + if value, ok := values[i].(*alpacadecimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field meter_value", values[i]) + } else if value != nil { + _m.MeterValue = *value + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ChargeUsageBasedRuns. +// This includes values selected through modifiers, order, etc. +func (_m *ChargeUsageBasedRuns) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryUsageBased queries the "usage_based" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryUsageBased() *ChargeUsageBasedQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryUsageBased(_m) +} + +// QueryCreditAllocations queries the "credit_allocations" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryCreditAllocations() *ChargeUsageBasedRunCreditAllocationsQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryCreditAllocations(_m) +} + +// QueryInvoicedUsage queries the "invoiced_usage" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryInvoicedUsage() *ChargeUsageBasedRunInvoicedUsageQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryInvoicedUsage(_m) +} + +// QueryPayment queries the "payment" edge of the ChargeUsageBasedRuns entity. +func (_m *ChargeUsageBasedRuns) QueryPayment() *ChargeUsageBasedRunPaymentQuery { + return NewChargeUsageBasedRunsClient(_m.config).QueryPayment(_m) +} + +// Update returns a builder for updating this ChargeUsageBasedRuns. +// Note that you need to call ChargeUsageBasedRuns.Unwrap() before calling this method if this ChargeUsageBasedRuns +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ChargeUsageBasedRuns) Update() *ChargeUsageBasedRunsUpdateOne { + return NewChargeUsageBasedRunsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ChargeUsageBasedRuns 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 (_m *ChargeUsageBasedRuns) Unwrap() *ChargeUsageBasedRuns { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: ChargeUsageBasedRuns is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ChargeUsageBasedRuns) String() string { + var builder strings.Builder + builder.WriteString("ChargeUsageBasedRuns(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("namespace=") + builder.WriteString(_m.Namespace) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.DeletedAt; v != nil { + builder.WriteString("deleted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("charge_id=") + builder.WriteString(_m.ChargeID) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("asof=") + builder.WriteString(_m.Asof.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("meter_value=") + builder.WriteString(fmt.Sprintf("%v", _m.MeterValue)) + builder.WriteByte(')') + return builder.String() +} + +// ChargeUsageBasedRunsSlice is a parsable slice of ChargeUsageBasedRuns. +type ChargeUsageBasedRunsSlice []*ChargeUsageBasedRuns diff --git a/openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go b/openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go new file mode 100644 index 0000000000..cc5dc11993 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go @@ -0,0 +1,230 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruns + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" +) + +const ( + // Label holds the string label denoting the chargeusagebasedruns type in the database. + Label = "charge_usage_based_runs" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldChargeID holds the string denoting the charge_id field in the database. + FieldChargeID = "charge_id" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldAsof holds the string denoting the asof field in the database. + FieldAsof = "asof" + // FieldMeterValue holds the string denoting the meter_value field in the database. + FieldMeterValue = "meter_value" + // EdgeUsageBased holds the string denoting the usage_based edge name in mutations. + EdgeUsageBased = "usage_based" + // EdgeCreditAllocations holds the string denoting the credit_allocations edge name in mutations. + EdgeCreditAllocations = "credit_allocations" + // EdgeInvoicedUsage holds the string denoting the invoiced_usage edge name in mutations. + EdgeInvoicedUsage = "invoiced_usage" + // EdgePayment holds the string denoting the payment edge name in mutations. + EdgePayment = "payment" + // Table holds the table name of the chargeusagebasedruns in the database. + Table = "charge_usage_based_runs" + // UsageBasedTable is the table that holds the usage_based relation/edge. + UsageBasedTable = "charge_usage_based_runs" + // UsageBasedInverseTable is the table name for the ChargeUsageBased entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebased" package. + UsageBasedInverseTable = "charge_usage_based" + // UsageBasedColumn is the table column denoting the usage_based relation/edge. + UsageBasedColumn = "charge_id" + // CreditAllocationsTable is the table that holds the credit_allocations relation/edge. + CreditAllocationsTable = "charge_usage_based_run_credit_allocations" + // CreditAllocationsInverseTable is the table name for the ChargeUsageBasedRunCreditAllocations entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruncreditallocations" package. + CreditAllocationsInverseTable = "charge_usage_based_run_credit_allocations" + // CreditAllocationsColumn is the table column denoting the credit_allocations relation/edge. + CreditAllocationsColumn = "run_id" + // InvoicedUsageTable is the table that holds the invoiced_usage relation/edge. + InvoicedUsageTable = "charge_usage_based_run_invoiced_usages" + // InvoicedUsageInverseTable is the table name for the ChargeUsageBasedRunInvoicedUsage entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedruninvoicedusage" package. + InvoicedUsageInverseTable = "charge_usage_based_run_invoiced_usages" + // InvoicedUsageColumn is the table column denoting the invoiced_usage relation/edge. + InvoicedUsageColumn = "run_id" + // PaymentTable is the table that holds the payment relation/edge. + PaymentTable = "charge_usage_based_run_payments" + // PaymentInverseTable is the table name for the ChargeUsageBasedRunPayment entity. + // It exists in this package in order to avoid circular dependency with the "chargeusagebasedrunpayment" package. + PaymentInverseTable = "charge_usage_based_run_payments" + // PaymentColumn is the table column denoting the payment relation/edge. + PaymentColumn = "run_id" +) + +// Columns holds all SQL columns for chargeusagebasedruns fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldCreatedAt, + FieldUpdatedAt, + FieldDeletedAt, + FieldChargeID, + FieldType, + FieldAsof, + FieldMeterValue, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + NamespaceValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() string +) + +// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. +func TypeValidator(_type usagebased.RealizationRunType) error { + switch _type { + case "invoice": + return nil + default: + return fmt.Errorf("chargeusagebasedruns: invalid enum value for type field: %q", _type) + } +} + +// OrderOption defines the ordering options for the ChargeUsageBasedRuns 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() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByChargeID orders the results by the charge_id field. +func ByChargeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChargeID, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByAsof orders the results by the asof field. +func ByAsof(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAsof, opts...).ToFunc() +} + +// ByMeterValue orders the results by the meter_value field. +func ByMeterValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMeterValue, opts...).ToFunc() +} + +// ByUsageBasedField orders the results by usage_based field. +func ByUsageBasedField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsageBasedStep(), sql.OrderByField(field, opts...)) + } +} + +// ByCreditAllocationsCount orders the results by credit_allocations count. +func ByCreditAllocationsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCreditAllocationsStep(), opts...) + } +} + +// ByCreditAllocations orders the results by credit_allocations terms. +func ByCreditAllocations(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCreditAllocationsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByInvoicedUsageField orders the results by invoiced_usage field. +func ByInvoicedUsageField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newInvoicedUsageStep(), sql.OrderByField(field, opts...)) + } +} + +// ByPaymentField orders the results by payment field. +func ByPaymentField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPaymentStep(), sql.OrderByField(field, opts...)) + } +} +func newUsageBasedStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsageBasedInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UsageBasedTable, UsageBasedColumn), + ) +} +func newCreditAllocationsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CreditAllocationsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CreditAllocationsTable, CreditAllocationsColumn), + ) +} +func newInvoicedUsageStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InvoicedUsageInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, InvoicedUsageTable, InvoicedUsageColumn), + ) +} +func newPaymentStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PaymentInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, PaymentTable, PaymentColumn), + ) +} diff --git a/openmeter/ent/db/chargeusagebasedruns/where.go b/openmeter/ent/db/chargeusagebasedruns/where.go new file mode 100644 index 0000000000..2d6a4945ac --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns/where.go @@ -0,0 +1,580 @@ +// Code generated by ent, DO NOT EDIT. + +package chargeusagebasedruns + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContainsFold(FieldID, id)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldNamespace, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldDeletedAt, v)) +} + +// ChargeID applies equality check predicate on the "charge_id" field. It's identical to ChargeIDEQ. +func ChargeID(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldChargeID, v)) +} + +// Asof applies equality check predicate on the "asof" field. It's identical to AsofEQ. +func Asof(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldAsof, v)) +} + +// MeterValue applies equality check predicate on the "meter_value" field. It's identical to MeterValueEQ. +func MeterValue(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldMeterValue, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContainsFold(FieldNamespace, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotNull(FieldDeletedAt)) +} + +// ChargeIDEQ applies the EQ predicate on the "charge_id" field. +func ChargeIDEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldChargeID, v)) +} + +// ChargeIDNEQ applies the NEQ predicate on the "charge_id" field. +func ChargeIDNEQ(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldChargeID, v)) +} + +// ChargeIDIn applies the In predicate on the "charge_id" field. +func ChargeIDIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldChargeID, vs...)) +} + +// ChargeIDNotIn applies the NotIn predicate on the "charge_id" field. +func ChargeIDNotIn(vs ...string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldChargeID, vs...)) +} + +// ChargeIDGT applies the GT predicate on the "charge_id" field. +func ChargeIDGT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldChargeID, v)) +} + +// ChargeIDGTE applies the GTE predicate on the "charge_id" field. +func ChargeIDGTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldChargeID, v)) +} + +// ChargeIDLT applies the LT predicate on the "charge_id" field. +func ChargeIDLT(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldChargeID, v)) +} + +// ChargeIDLTE applies the LTE predicate on the "charge_id" field. +func ChargeIDLTE(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldChargeID, v)) +} + +// ChargeIDContains applies the Contains predicate on the "charge_id" field. +func ChargeIDContains(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContains(FieldChargeID, v)) +} + +// ChargeIDHasPrefix applies the HasPrefix predicate on the "charge_id" field. +func ChargeIDHasPrefix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasPrefix(FieldChargeID, v)) +} + +// ChargeIDHasSuffix applies the HasSuffix predicate on the "charge_id" field. +func ChargeIDHasSuffix(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldHasSuffix(FieldChargeID, v)) +} + +// ChargeIDEqualFold applies the EqualFold predicate on the "charge_id" field. +func ChargeIDEqualFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEqualFold(FieldChargeID, v)) +} + +// ChargeIDContainsFold applies the ContainsFold predicate on the "charge_id" field. +func ChargeIDContainsFold(v string) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldContainsFold(FieldChargeID, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + vc := v + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + vc := v + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...usagebased.RealizationRunType) predicate.ChargeUsageBasedRuns { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldType, v...)) +} + +// AsofEQ applies the EQ predicate on the "asof" field. +func AsofEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldAsof, v)) +} + +// AsofNEQ applies the NEQ predicate on the "asof" field. +func AsofNEQ(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldAsof, v)) +} + +// AsofIn applies the In predicate on the "asof" field. +func AsofIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldAsof, vs...)) +} + +// AsofNotIn applies the NotIn predicate on the "asof" field. +func AsofNotIn(vs ...time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldAsof, vs...)) +} + +// AsofGT applies the GT predicate on the "asof" field. +func AsofGT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldAsof, v)) +} + +// AsofGTE applies the GTE predicate on the "asof" field. +func AsofGTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldAsof, v)) +} + +// AsofLT applies the LT predicate on the "asof" field. +func AsofLT(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldAsof, v)) +} + +// AsofLTE applies the LTE predicate on the "asof" field. +func AsofLTE(v time.Time) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldAsof, v)) +} + +// MeterValueEQ applies the EQ predicate on the "meter_value" field. +func MeterValueEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldEQ(FieldMeterValue, v)) +} + +// MeterValueNEQ applies the NEQ predicate on the "meter_value" field. +func MeterValueNEQ(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNEQ(FieldMeterValue, v)) +} + +// MeterValueIn applies the In predicate on the "meter_value" field. +func MeterValueIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldIn(FieldMeterValue, vs...)) +} + +// MeterValueNotIn applies the NotIn predicate on the "meter_value" field. +func MeterValueNotIn(vs ...alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldNotIn(FieldMeterValue, vs...)) +} + +// MeterValueGT applies the GT predicate on the "meter_value" field. +func MeterValueGT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGT(FieldMeterValue, v)) +} + +// MeterValueGTE applies the GTE predicate on the "meter_value" field. +func MeterValueGTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldGTE(FieldMeterValue, v)) +} + +// MeterValueLT applies the LT predicate on the "meter_value" field. +func MeterValueLT(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLT(FieldMeterValue, v)) +} + +// MeterValueLTE applies the LTE predicate on the "meter_value" field. +func MeterValueLTE(v alpacadecimal.Decimal) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.FieldLTE(FieldMeterValue, v)) +} + +// HasUsageBased applies the HasEdge predicate on the "usage_based" edge. +func HasUsageBased() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UsageBasedTable, UsageBasedColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsageBasedWith applies the HasEdge predicate on the "usage_based" edge with a given conditions (other predicates). +func HasUsageBasedWith(preds ...predicate.ChargeUsageBased) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newUsageBasedStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCreditAllocations applies the HasEdge predicate on the "credit_allocations" edge. +func HasCreditAllocations() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CreditAllocationsTable, CreditAllocationsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCreditAllocationsWith applies the HasEdge predicate on the "credit_allocations" edge with a given conditions (other predicates). +func HasCreditAllocationsWith(preds ...predicate.ChargeUsageBasedRunCreditAllocations) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newCreditAllocationsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasInvoicedUsage applies the HasEdge predicate on the "invoiced_usage" edge. +func HasInvoicedUsage() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, InvoicedUsageTable, InvoicedUsageColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInvoicedUsageWith applies the HasEdge predicate on the "invoiced_usage" edge with a given conditions (other predicates). +func HasInvoicedUsageWith(preds ...predicate.ChargeUsageBasedRunInvoicedUsage) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newInvoicedUsageStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasPayment applies the HasEdge predicate on the "payment" edge. +func HasPayment() predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, PaymentTable, PaymentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPaymentWith applies the HasEdge predicate on the "payment" edge with a given conditions (other predicates). +func HasPaymentWith(preds ...predicate.ChargeUsageBasedRunPayment) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(func(s *sql.Selector) { + step := newPaymentStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ChargeUsageBasedRuns) predicate.ChargeUsageBasedRuns { + return predicate.ChargeUsageBasedRuns(sql.NotPredicates(p)) +} diff --git a/openmeter/ent/db/chargeusagebasedruns_create.go b/openmeter/ent/db/chargeusagebasedruns_create.go new file mode 100644 index 0000000000..c163e9af14 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns_create.go @@ -0,0 +1,936 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" +) + +// ChargeUsageBasedRunsCreate is the builder for creating a ChargeUsageBasedRuns entity. +type ChargeUsageBasedRunsCreate struct { + config + mutation *ChargeUsageBasedRunsMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNamespace sets the "namespace" field. +func (_c *ChargeUsageBasedRunsCreate) SetNamespace(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetNamespace(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ChargeUsageBasedRunsCreate) SetCreatedAt(v time.Time) *ChargeUsageBasedRunsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableCreatedAt(v *time.Time) *ChargeUsageBasedRunsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ChargeUsageBasedRunsCreate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunsCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableUpdatedAt(v *time.Time) *ChargeUsageBasedRunsCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *ChargeUsageBasedRunsCreate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunsCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunsCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetChargeID sets the "charge_id" field. +func (_c *ChargeUsageBasedRunsCreate) SetChargeID(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetChargeID(v) + return _c +} + +// SetType sets the "type" field. +func (_c *ChargeUsageBasedRunsCreate) SetType(v usagebased.RealizationRunType) *ChargeUsageBasedRunsCreate { + _c.mutation.SetType(v) + return _c +} + +// SetAsof sets the "asof" field. +func (_c *ChargeUsageBasedRunsCreate) SetAsof(v time.Time) *ChargeUsageBasedRunsCreate { + _c.mutation.SetAsof(v) + return _c +} + +// SetMeterValue sets the "meter_value" field. +func (_c *ChargeUsageBasedRunsCreate) SetMeterValue(v alpacadecimal.Decimal) *ChargeUsageBasedRunsCreate { + _c.mutation.SetMeterValue(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ChargeUsageBasedRunsCreate) SetID(v string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableID(v *string) *ChargeUsageBasedRunsCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by ID. +func (_c *ChargeUsageBasedRunsCreate) SetUsageBasedID(id string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetUsageBasedID(id) + return _c +} + +// SetUsageBased sets the "usage_based" edge to the ChargeUsageBased entity. +func (_c *ChargeUsageBasedRunsCreate) SetUsageBased(v *ChargeUsageBased) *ChargeUsageBasedRunsCreate { + return _c.SetUsageBasedID(v.ID) +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (_c *ChargeUsageBasedRunsCreate) AddCreditAllocationIDs(ids ...string) *ChargeUsageBasedRunsCreate { + _c.mutation.AddCreditAllocationIDs(ids...) + return _c +} + +// AddCreditAllocations adds the "credit_allocations" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_c *ChargeUsageBasedRunsCreate) AddCreditAllocations(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunsCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddCreditAllocationIDs(ids...) +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by ID. +func (_c *ChargeUsageBasedRunsCreate) SetInvoicedUsageID(id string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetInvoicedUsageID(id) + return _c +} + +// SetNillableInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillableInvoicedUsageID(id *string) *ChargeUsageBasedRunsCreate { + if id != nil { + _c = _c.SetInvoicedUsageID(*id) + } + return _c +} + +// SetInvoicedUsage sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity. +func (_c *ChargeUsageBasedRunsCreate) SetInvoicedUsage(v *ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunsCreate { + return _c.SetInvoicedUsageID(v.ID) +} + +// SetPaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by ID. +func (_c *ChargeUsageBasedRunsCreate) SetPaymentID(id string) *ChargeUsageBasedRunsCreate { + _c.mutation.SetPaymentID(id) + return _c +} + +// SetNillablePaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by ID if the given value is not nil. +func (_c *ChargeUsageBasedRunsCreate) SetNillablePaymentID(id *string) *ChargeUsageBasedRunsCreate { + if id != nil { + _c = _c.SetPaymentID(*id) + } + return _c +} + +// SetPayment sets the "payment" edge to the ChargeUsageBasedRunPayment entity. +func (_c *ChargeUsageBasedRunsCreate) SetPayment(v *ChargeUsageBasedRunPayment) *ChargeUsageBasedRunsCreate { + return _c.SetPaymentID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunsMutation object of the builder. +func (_c *ChargeUsageBasedRunsCreate) Mutation() *ChargeUsageBasedRunsMutation { + return _c.mutation +} + +// Save creates the ChargeUsageBasedRuns in the database. +func (_c *ChargeUsageBasedRunsCreate) Save(ctx context.Context) (*ChargeUsageBasedRuns, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ChargeUsageBasedRunsCreate) SaveX(ctx context.Context) *ChargeUsageBasedRuns { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunsCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ChargeUsageBasedRunsCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := chargeusagebasedruns.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruns.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := chargeusagebasedruns.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ChargeUsageBasedRunsCreate) check() error { + if _, ok := _c.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.namespace"`)} + } + if v, ok := _c.mutation.Namespace(); ok { + if err := chargeusagebasedruns.NamespaceValidator(v); err != nil { + return &ValidationError{Name: "namespace", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.namespace": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.updated_at"`)} + } + if _, ok := _c.mutation.ChargeID(); !ok { + return &ValidationError{Name: "charge_id", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.charge_id"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := chargeusagebasedruns.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "ChargeUsageBasedRuns.type": %w`, err)} + } + } + if _, ok := _c.mutation.Asof(); !ok { + return &ValidationError{Name: "asof", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.asof"`)} + } + if _, ok := _c.mutation.MeterValue(); !ok { + return &ValidationError{Name: "meter_value", err: errors.New(`db: missing required field "ChargeUsageBasedRuns.meter_value"`)} + } + if len(_c.mutation.UsageBasedIDs()) == 0 { + return &ValidationError{Name: "usage_based", err: errors.New(`db: missing required edge "ChargeUsageBasedRuns.usage_based"`)} + } + return nil +} + +func (_c *ChargeUsageBasedRunsCreate) sqlSave(ctx context.Context) (*ChargeUsageBasedRuns, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected ChargeUsageBasedRuns.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ChargeUsageBasedRunsCreate) createSpec() (*ChargeUsageBasedRuns, *sqlgraph.CreateSpec) { + var ( + _node = &ChargeUsageBasedRuns{config: _c.config} + _spec = sqlgraph.NewCreateSpec(chargeusagebasedruns.Table, sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Namespace(); ok { + _spec.SetField(chargeusagebasedruns.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = &value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(chargeusagebasedruns.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.Asof(); ok { + _spec.SetField(chargeusagebasedruns.FieldAsof, field.TypeTime, value) + _node.Asof = value + } + if value, ok := _c.mutation.MeterValue(); ok { + _spec.SetField(chargeusagebasedruns.FieldMeterValue, field.TypeOther, value) + _node.MeterValue = value + } + if nodes := _c.mutation.UsageBasedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: chargeusagebasedruns.UsageBasedTable, + Columns: []string{chargeusagebasedruns.UsageBasedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebased.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ChargeID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.CreditAllocationsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.InvoicedUsageIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.InvoicedUsageTable, + Columns: []string{chargeusagebasedruns.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.PaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.PaymentTable, + Columns: []string{chargeusagebasedruns.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRuns.Create(). +// SetNamespace(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunsUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunsCreate) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunsUpsertOne { + _c.conflict = opts + return &ChargeUsageBasedRunsUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRuns.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunsCreate) OnConflictColumns(columns ...string) *ChargeUsageBasedRunsUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunsUpsertOne{ + create: _c, + } +} + +type ( + // ChargeUsageBasedRunsUpsertOne is the builder for "upsert"-ing + // one ChargeUsageBasedRuns node. + ChargeUsageBasedRunsUpsertOne struct { + create *ChargeUsageBasedRunsCreate + } + + // ChargeUsageBasedRunsUpsert is the "OnConflict" setter. + ChargeUsageBasedRunsUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunsUpsert) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateUpdatedAt() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldUpdatedAt) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunsUpsert) SetDeletedAt(v time.Time) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateDeletedAt() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunsUpsert) ClearDeletedAt() *ChargeUsageBasedRunsUpsert { + u.SetNull(chargeusagebasedruns.FieldDeletedAt) + return u +} + +// SetAsof sets the "asof" field. +func (u *ChargeUsageBasedRunsUpsert) SetAsof(v time.Time) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldAsof, v) + return u +} + +// UpdateAsof sets the "asof" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateAsof() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldAsof) + return u +} + +// SetMeterValue sets the "meter_value" field. +func (u *ChargeUsageBasedRunsUpsert) SetMeterValue(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsert { + u.Set(chargeusagebasedruns.FieldMeterValue, v) + return u +} + +// UpdateMeterValue sets the "meter_value" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsert) UpdateMeterValue() *ChargeUsageBasedRunsUpsert { + u.SetExcluded(chargeusagebasedruns.FieldMeterValue) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRuns.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedruns.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunsUpsertOne) UpdateNewValues() *ChargeUsageBasedRunsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldID) + } + if _, exists := u.create.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedruns.FieldNamespace) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedruns.FieldCreatedAt) + } + if _, exists := u.create.mutation.ChargeID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldChargeID) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(chargeusagebasedruns.FieldType) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRuns.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunsUpsertOne) Ignore() *ChargeUsageBasedRunsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunsUpsertOne) DoNothing() *ChargeUsageBasedRunsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunsCreate.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunsUpsertOne) Update(set func(*ChargeUsageBasedRunsUpsert)) *ChargeUsageBasedRunsUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunsUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateUpdatedAt() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateDeletedAt() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunsUpsertOne) ClearDeletedAt() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAsof sets the "asof" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetAsof(v time.Time) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetAsof(v) + }) +} + +// UpdateAsof sets the "asof" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateAsof() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateAsof() + }) +} + +// SetMeterValue sets the "meter_value" field. +func (u *ChargeUsageBasedRunsUpsertOne) SetMeterValue(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetMeterValue(v) + }) +} + +// UpdateMeterValue sets the "meter_value" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertOne) UpdateMeterValue() *ChargeUsageBasedRunsUpsertOne { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateMeterValue() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunsUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunsCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunsUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ChargeUsageBasedRunsUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: ChargeUsageBasedRunsUpsertOne.ID is not supported by MySQL driver. Use ChargeUsageBasedRunsUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ChargeUsageBasedRunsUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ChargeUsageBasedRunsCreateBulk is the builder for creating many ChargeUsageBasedRuns entities in bulk. +type ChargeUsageBasedRunsCreateBulk struct { + config + err error + builders []*ChargeUsageBasedRunsCreate + conflict []sql.ConflictOption +} + +// Save creates the ChargeUsageBasedRuns entities in the database. +func (_c *ChargeUsageBasedRunsCreateBulk) Save(ctx context.Context) ([]*ChargeUsageBasedRuns, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ChargeUsageBasedRuns, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ChargeUsageBasedRunsMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ChargeUsageBasedRunsCreateBulk) SaveX(ctx context.Context) []*ChargeUsageBasedRuns { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ChargeUsageBasedRunsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ChargeUsageBasedRunsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ChargeUsageBasedRuns.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ChargeUsageBasedRunsUpsert) { +// SetNamespace(v+v). +// }). +// Exec(ctx) +func (_c *ChargeUsageBasedRunsCreateBulk) OnConflict(opts ...sql.ConflictOption) *ChargeUsageBasedRunsUpsertBulk { + _c.conflict = opts + return &ChargeUsageBasedRunsUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRuns.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ChargeUsageBasedRunsCreateBulk) OnConflictColumns(columns ...string) *ChargeUsageBasedRunsUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ChargeUsageBasedRunsUpsertBulk{ + create: _c, + } +} + +// ChargeUsageBasedRunsUpsertBulk is the builder for "upsert"-ing +// a bulk of ChargeUsageBasedRuns nodes. +type ChargeUsageBasedRunsUpsertBulk struct { + create *ChargeUsageBasedRunsCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ChargeUsageBasedRuns.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(chargeusagebasedruns.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateNewValues() *ChargeUsageBasedRunsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldID) + } + if _, exists := b.mutation.Namespace(); exists { + s.SetIgnore(chargeusagebasedruns.FieldNamespace) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(chargeusagebasedruns.FieldCreatedAt) + } + if _, exists := b.mutation.ChargeID(); exists { + s.SetIgnore(chargeusagebasedruns.FieldChargeID) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(chargeusagebasedruns.FieldType) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ChargeUsageBasedRuns.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ChargeUsageBasedRunsUpsertBulk) Ignore() *ChargeUsageBasedRunsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ChargeUsageBasedRunsUpsertBulk) DoNothing() *ChargeUsageBasedRunsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ChargeUsageBasedRunsCreateBulk.OnConflict +// documentation for more info. +func (u *ChargeUsageBasedRunsUpsertBulk) Update(set func(*ChargeUsageBasedRunsUpsert)) *ChargeUsageBasedRunsUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ChargeUsageBasedRunsUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateUpdatedAt() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetDeletedAt(v time.Time) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateDeletedAt() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *ChargeUsageBasedRunsUpsertBulk) ClearDeletedAt() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.ClearDeletedAt() + }) +} + +// SetAsof sets the "asof" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetAsof(v time.Time) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetAsof(v) + }) +} + +// UpdateAsof sets the "asof" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateAsof() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateAsof() + }) +} + +// SetMeterValue sets the "meter_value" field. +func (u *ChargeUsageBasedRunsUpsertBulk) SetMeterValue(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.SetMeterValue(v) + }) +} + +// UpdateMeterValue sets the "meter_value" field to the value that was provided on create. +func (u *ChargeUsageBasedRunsUpsertBulk) UpdateMeterValue() *ChargeUsageBasedRunsUpsertBulk { + return u.Update(func(s *ChargeUsageBasedRunsUpsert) { + s.UpdateMeterValue() + }) +} + +// Exec executes the query. +func (u *ChargeUsageBasedRunsUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ChargeUsageBasedRunsCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ChargeUsageBasedRunsCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ChargeUsageBasedRunsUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedruns_delete.go b/openmeter/ent/db/chargeusagebasedruns_delete.go new file mode 100644 index 0000000000..2e02a37f2e --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunsDelete is the builder for deleting a ChargeUsageBasedRuns entity. +type ChargeUsageBasedRunsDelete struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunsMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunsDelete builder. +func (_d *ChargeUsageBasedRunsDelete) Where(ps ...predicate.ChargeUsageBasedRuns) *ChargeUsageBasedRunsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ChargeUsageBasedRunsDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ChargeUsageBasedRunsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(chargeusagebasedruns.Table, sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ChargeUsageBasedRunsDeleteOne is the builder for deleting a single ChargeUsageBasedRuns entity. +type ChargeUsageBasedRunsDeleteOne struct { + _d *ChargeUsageBasedRunsDelete +} + +// Where appends a list predicates to the ChargeUsageBasedRunsDelete builder. +func (_d *ChargeUsageBasedRunsDeleteOne) Where(ps ...predicate.ChargeUsageBasedRuns) *ChargeUsageBasedRunsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ChargeUsageBasedRunsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{chargeusagebasedruns.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ChargeUsageBasedRunsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/openmeter/ent/db/chargeusagebasedruns_query.go b/openmeter/ent/db/chargeusagebasedruns_query.go new file mode 100644 index 0000000000..6b123cfc74 --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns_query.go @@ -0,0 +1,860 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunsQuery is the builder for querying ChargeUsageBasedRuns entities. +type ChargeUsageBasedRunsQuery struct { + config + ctx *QueryContext + order []chargeusagebasedruns.OrderOption + inters []Interceptor + predicates []predicate.ChargeUsageBasedRuns + withUsageBased *ChargeUsageBasedQuery + withCreditAllocations *ChargeUsageBasedRunCreditAllocationsQuery + withInvoicedUsage *ChargeUsageBasedRunInvoicedUsageQuery + withPayment *ChargeUsageBasedRunPaymentQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ChargeUsageBasedRunsQuery builder. +func (_q *ChargeUsageBasedRunsQuery) Where(ps ...predicate.ChargeUsageBasedRuns) *ChargeUsageBasedRunsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ChargeUsageBasedRunsQuery) Limit(limit int) *ChargeUsageBasedRunsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ChargeUsageBasedRunsQuery) Offset(offset int) *ChargeUsageBasedRunsQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ChargeUsageBasedRunsQuery) Unique(unique bool) *ChargeUsageBasedRunsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ChargeUsageBasedRunsQuery) Order(o ...chargeusagebasedruns.OrderOption) *ChargeUsageBasedRunsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryUsageBased chains the current query on the "usage_based" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryUsageBased() *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, selector), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruns.UsageBasedTable, chargeusagebasedruns.UsageBasedColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCreditAllocations chains the current query on the "credit_allocations" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryCreditAllocations() *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, selector), + sqlgraph.To(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebasedruns.CreditAllocationsTable, chargeusagebasedruns.CreditAllocationsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryInvoicedUsage chains the current query on the "invoiced_usage" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryInvoicedUsage() *ChargeUsageBasedRunInvoicedUsageQuery { + query := (&ChargeUsageBasedRunInvoicedUsageClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, selector), + sqlgraph.To(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeusagebasedruns.InvoicedUsageTable, chargeusagebasedruns.InvoicedUsageColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryPayment chains the current query on the "payment" edge. +func (_q *ChargeUsageBasedRunsQuery) QueryPayment() *ChargeUsageBasedRunPaymentQuery { + query := (&ChargeUsageBasedRunPaymentClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, selector), + sqlgraph.To(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeusagebasedruns.PaymentTable, chargeusagebasedruns.PaymentColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ChargeUsageBasedRuns entity from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRuns was found. +func (_q *ChargeUsageBasedRunsQuery) First(ctx context.Context) (*ChargeUsageBasedRuns, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{chargeusagebasedruns.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) FirstX(ctx context.Context) *ChargeUsageBasedRuns { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ChargeUsageBasedRuns ID from the query. +// Returns a *NotFoundError when no ChargeUsageBasedRuns ID was found. +func (_q *ChargeUsageBasedRunsQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{chargeusagebasedruns.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ChargeUsageBasedRuns entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ChargeUsageBasedRuns entity is found. +// Returns a *NotFoundError when no ChargeUsageBasedRuns entities are found. +func (_q *ChargeUsageBasedRunsQuery) Only(ctx context.Context) (*ChargeUsageBasedRuns, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{chargeusagebasedruns.Label} + default: + return nil, &NotSingularError{chargeusagebasedruns.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) OnlyX(ctx context.Context) *ChargeUsageBasedRuns { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ChargeUsageBasedRuns ID in the query. +// Returns a *NotSingularError when more than one ChargeUsageBasedRuns ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ChargeUsageBasedRunsQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{chargeusagebasedruns.Label} + default: + err = &NotSingularError{chargeusagebasedruns.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ChargeUsageBasedRunsSlice. +func (_q *ChargeUsageBasedRunsQuery) All(ctx context.Context) ([]*ChargeUsageBasedRuns, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ChargeUsageBasedRuns, *ChargeUsageBasedRunsQuery]() + return withInterceptors[[]*ChargeUsageBasedRuns](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) AllX(ctx context.Context) []*ChargeUsageBasedRuns { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ChargeUsageBasedRuns IDs. +func (_q *ChargeUsageBasedRunsQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(chargeusagebasedruns.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ChargeUsageBasedRunsQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ChargeUsageBasedRunsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ChargeUsageBasedRunsQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ChargeUsageBasedRunsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ChargeUsageBasedRunsQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ChargeUsageBasedRunsQuery) Clone() *ChargeUsageBasedRunsQuery { + if _q == nil { + return nil + } + return &ChargeUsageBasedRunsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]chargeusagebasedruns.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ChargeUsageBasedRuns{}, _q.predicates...), + withUsageBased: _q.withUsageBased.Clone(), + withCreditAllocations: _q.withCreditAllocations.Clone(), + withInvoicedUsage: _q.withInvoicedUsage.Clone(), + withPayment: _q.withPayment.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithUsageBased tells the query-builder to eager-load the nodes that are connected to +// the "usage_based" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithUsageBased(opts ...func(*ChargeUsageBasedQuery)) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUsageBased = query + return _q +} + +// WithCreditAllocations tells the query-builder to eager-load the nodes that are connected to +// the "credit_allocations" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithCreditAllocations(opts ...func(*ChargeUsageBasedRunCreditAllocationsQuery)) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withCreditAllocations = query + return _q +} + +// WithInvoicedUsage tells the query-builder to eager-load the nodes that are connected to +// the "invoiced_usage" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithInvoicedUsage(opts ...func(*ChargeUsageBasedRunInvoicedUsageQuery)) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunInvoicedUsageClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withInvoicedUsage = query + return _q +} + +// WithPayment tells the query-builder to eager-load the nodes that are connected to +// the "payment" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ChargeUsageBasedRunsQuery) WithPayment(opts ...func(*ChargeUsageBasedRunPaymentQuery)) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunPaymentClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPayment = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Namespace string `json:"namespace,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ChargeUsageBasedRuns.Query(). +// GroupBy(chargeusagebasedruns.FieldNamespace). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunsQuery) GroupBy(field string, fields ...string) *ChargeUsageBasedRunsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ChargeUsageBasedRunsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = chargeusagebasedruns.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Namespace string `json:"namespace,omitempty"` +// } +// +// client.ChargeUsageBasedRuns.Query(). +// Select(chargeusagebasedruns.FieldNamespace). +// Scan(ctx, &v) +func (_q *ChargeUsageBasedRunsQuery) Select(fields ...string) *ChargeUsageBasedRunsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ChargeUsageBasedRunsSelect{ChargeUsageBasedRunsQuery: _q} + sbuild.label = chargeusagebasedruns.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ChargeUsageBasedRunsSelect configured with the given aggregations. +func (_q *ChargeUsageBasedRunsQuery) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ChargeUsageBasedRunsQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !chargeusagebasedruns.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ChargeUsageBasedRunsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ChargeUsageBasedRuns, error) { + var ( + nodes = []*ChargeUsageBasedRuns{} + _spec = _q.querySpec() + loadedTypes = [4]bool{ + _q.withUsageBased != nil, + _q.withCreditAllocations != nil, + _q.withInvoicedUsage != nil, + _q.withPayment != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ChargeUsageBasedRuns).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ChargeUsageBasedRuns{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withUsageBased; query != nil { + if err := _q.loadUsageBased(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRuns, e *ChargeUsageBased) { n.Edges.UsageBased = e }); err != nil { + return nil, err + } + } + if query := _q.withCreditAllocations; query != nil { + if err := _q.loadCreditAllocations(ctx, query, nodes, + func(n *ChargeUsageBasedRuns) { n.Edges.CreditAllocations = []*ChargeUsageBasedRunCreditAllocations{} }, + func(n *ChargeUsageBasedRuns, e *ChargeUsageBasedRunCreditAllocations) { + n.Edges.CreditAllocations = append(n.Edges.CreditAllocations, e) + }); err != nil { + return nil, err + } + } + if query := _q.withInvoicedUsage; query != nil { + if err := _q.loadInvoicedUsage(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRuns, e *ChargeUsageBasedRunInvoicedUsage) { n.Edges.InvoicedUsage = e }); err != nil { + return nil, err + } + } + if query := _q.withPayment; query != nil { + if err := _q.loadPayment(ctx, query, nodes, nil, + func(n *ChargeUsageBasedRuns, e *ChargeUsageBasedRunPayment) { n.Edges.Payment = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ChargeUsageBasedRunsQuery) loadUsageBased(ctx context.Context, query *ChargeUsageBasedQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *ChargeUsageBased)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*ChargeUsageBasedRuns) + for i := range nodes { + fk := nodes[i].ChargeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(chargeusagebased.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "charge_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ChargeUsageBasedRunsQuery) loadCreditAllocations(ctx context.Context, query *ChargeUsageBasedRunCreditAllocationsQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *ChargeUsageBasedRunCreditAllocations)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeUsageBasedRuns) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(chargeusagebasedruncreditallocations.FieldRunID) + } + query.Where(predicate.ChargeUsageBasedRunCreditAllocations(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebasedruns.CreditAllocationsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RunID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "run_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeUsageBasedRunsQuery) loadInvoicedUsage(ctx context.Context, query *ChargeUsageBasedRunInvoicedUsageQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *ChargeUsageBasedRunInvoicedUsage)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeUsageBasedRuns) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(chargeusagebasedruninvoicedusage.FieldRunID) + } + query.Where(predicate.ChargeUsageBasedRunInvoicedUsage(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebasedruns.InvoicedUsageColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RunID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "run_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ChargeUsageBasedRunsQuery) loadPayment(ctx context.Context, query *ChargeUsageBasedRunPaymentQuery, nodes []*ChargeUsageBasedRuns, init func(*ChargeUsageBasedRuns), assign func(*ChargeUsageBasedRuns, *ChargeUsageBasedRunPayment)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*ChargeUsageBasedRuns) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(chargeusagebasedrunpayment.FieldRunID) + } + query.Where(predicate.ChargeUsageBasedRunPayment(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(chargeusagebasedruns.PaymentColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RunID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "run_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *ChargeUsageBasedRunsQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ChargeUsageBasedRunsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(chargeusagebasedruns.Table, chargeusagebasedruns.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedruns.FieldID) + for i := range fields { + if fields[i] != chargeusagebasedruns.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withUsageBased != nil { + _spec.Node.AddColumnOnce(chargeusagebasedruns.FieldChargeID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ChargeUsageBasedRunsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(chargeusagebasedruns.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = chargeusagebasedruns.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *ChargeUsageBasedRunsQuery) ForUpdate(opts ...sql.LockOption) *ChargeUsageBasedRunsQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *ChargeUsageBasedRunsQuery) ForShare(opts ...sql.LockOption) *ChargeUsageBasedRunsQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ChargeUsageBasedRunsGroupBy is the group-by builder for ChargeUsageBasedRuns entities. +type ChargeUsageBasedRunsGroupBy struct { + selector + build *ChargeUsageBasedRunsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ChargeUsageBasedRunsGroupBy) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ChargeUsageBasedRunsGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunsQuery, *ChargeUsageBasedRunsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ChargeUsageBasedRunsGroupBy) sqlScan(ctx context.Context, root *ChargeUsageBasedRunsQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ChargeUsageBasedRunsSelect is the builder for selecting fields of ChargeUsageBasedRuns entities. +type ChargeUsageBasedRunsSelect struct { + *ChargeUsageBasedRunsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ChargeUsageBasedRunsSelect) Aggregate(fns ...AggregateFunc) *ChargeUsageBasedRunsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ChargeUsageBasedRunsSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ChargeUsageBasedRunsQuery, *ChargeUsageBasedRunsSelect](ctx, _s.ChargeUsageBasedRunsQuery, _s, _s.inters, v) +} + +func (_s *ChargeUsageBasedRunsSelect) sqlScan(ctx context.Context, root *ChargeUsageBasedRunsQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/openmeter/ent/db/chargeusagebasedruns_update.go b/openmeter/ent/db/chargeusagebasedruns_update.go new file mode 100644 index 0000000000..7a9920d02e --- /dev/null +++ b/openmeter/ent/db/chargeusagebasedruns_update.go @@ -0,0 +1,736 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" + "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" +) + +// ChargeUsageBasedRunsUpdate is the builder for updating ChargeUsageBasedRuns entities. +type ChargeUsageBasedRunsUpdate struct { + config + hooks []Hook + mutation *ChargeUsageBasedRunsMutation +} + +// Where appends a list predicates to the ChargeUsageBasedRunsUpdate builder. +func (_u *ChargeUsageBasedRunsUpdate) Where(ps ...predicate.ChargeUsageBasedRuns) *ChargeUsageBasedRunsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunsUpdate) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunsUpdate) SetDeletedAt(v time.Time) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunsUpdate) ClearDeletedAt() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAsof sets the "asof" field. +func (_u *ChargeUsageBasedRunsUpdate) SetAsof(v time.Time) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetAsof(v) + return _u +} + +// SetNillableAsof sets the "asof" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableAsof(v *time.Time) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetAsof(*v) + } + return _u +} + +// SetMeterValue sets the "meter_value" field. +func (_u *ChargeUsageBasedRunsUpdate) SetMeterValue(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetMeterValue(v) + return _u +} + +// SetNillableMeterValue sets the "meter_value" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableMeterValue(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdate { + if v != nil { + _u.SetMeterValue(*v) + } + return _u +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (_u *ChargeUsageBasedRunsUpdate) AddCreditAllocationIDs(ids ...string) *ChargeUsageBasedRunsUpdate { + _u.mutation.AddCreditAllocationIDs(ids...) + return _u +} + +// AddCreditAllocations adds the "credit_allocations" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunsUpdate) AddCreditAllocations(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCreditAllocationIDs(ids...) +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by ID. +func (_u *ChargeUsageBasedRunsUpdate) SetInvoicedUsageID(id string) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetInvoicedUsageID(id) + return _u +} + +// SetNillableInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillableInvoicedUsageID(id *string) *ChargeUsageBasedRunsUpdate { + if id != nil { + _u = _u.SetInvoicedUsageID(*id) + } + return _u +} + +// SetInvoicedUsage sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity. +func (_u *ChargeUsageBasedRunsUpdate) SetInvoicedUsage(v *ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunsUpdate { + return _u.SetInvoicedUsageID(v.ID) +} + +// SetPaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by ID. +func (_u *ChargeUsageBasedRunsUpdate) SetPaymentID(id string) *ChargeUsageBasedRunsUpdate { + _u.mutation.SetPaymentID(id) + return _u +} + +// SetNillablePaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdate) SetNillablePaymentID(id *string) *ChargeUsageBasedRunsUpdate { + if id != nil { + _u = _u.SetPaymentID(*id) + } + return _u +} + +// SetPayment sets the "payment" edge to the ChargeUsageBasedRunPayment entity. +func (_u *ChargeUsageBasedRunsUpdate) SetPayment(v *ChargeUsageBasedRunPayment) *ChargeUsageBasedRunsUpdate { + return _u.SetPaymentID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunsMutation object of the builder. +func (_u *ChargeUsageBasedRunsUpdate) Mutation() *ChargeUsageBasedRunsMutation { + return _u.mutation +} + +// ClearCreditAllocations clears all "credit_allocations" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunsUpdate) ClearCreditAllocations() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearCreditAllocations() + return _u +} + +// RemoveCreditAllocationIDs removes the "credit_allocations" edge to ChargeUsageBasedRunCreditAllocations entities by IDs. +func (_u *ChargeUsageBasedRunsUpdate) RemoveCreditAllocationIDs(ids ...string) *ChargeUsageBasedRunsUpdate { + _u.mutation.RemoveCreditAllocationIDs(ids...) + return _u +} + +// RemoveCreditAllocations removes "credit_allocations" edges to ChargeUsageBasedRunCreditAllocations entities. +func (_u *ChargeUsageBasedRunsUpdate) RemoveCreditAllocations(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunsUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCreditAllocationIDs(ids...) +} + +// ClearInvoicedUsage clears the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity. +func (_u *ChargeUsageBasedRunsUpdate) ClearInvoicedUsage() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearInvoicedUsage() + return _u +} + +// ClearPayment clears the "payment" edge to the ChargeUsageBasedRunPayment entity. +func (_u *ChargeUsageBasedRunsUpdate) ClearPayment() *ChargeUsageBasedRunsUpdate { + _u.mutation.ClearPayment() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ChargeUsageBasedRunsUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ChargeUsageBasedRunsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunsUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunsUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruns.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunsUpdate) check() error { + if _u.mutation.UsageBasedCleared() && len(_u.mutation.UsageBasedIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRuns.usage_based"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedruns.Table, chargeusagebasedruns.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedruns.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Asof(); ok { + _spec.SetField(chargeusagebasedruns.FieldAsof, field.TypeTime, value) + } + if value, ok := _u.mutation.MeterValue(); ok { + _spec.SetField(chargeusagebasedruns.FieldMeterValue, field.TypeOther, value) + } + if _u.mutation.CreditAllocationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCreditAllocationsIDs(); len(nodes) > 0 && !_u.mutation.CreditAllocationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CreditAllocationsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.InvoicedUsageCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.InvoicedUsageTable, + Columns: []string{chargeusagebasedruns.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InvoicedUsageIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.InvoicedUsageTable, + Columns: []string{chargeusagebasedruns.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.PaymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.PaymentTable, + Columns: []string{chargeusagebasedruns.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.PaymentTable, + Columns: []string{chargeusagebasedruns.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedruns.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ChargeUsageBasedRunsUpdateOne is the builder for updating a single ChargeUsageBasedRuns entity. +type ChargeUsageBasedRunsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ChargeUsageBasedRunsMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetUpdatedAt(v time.Time) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetDeletedAt(v time.Time) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableDeletedAt(v *time.Time) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearDeletedAt() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetAsof sets the "asof" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetAsof(v time.Time) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetAsof(v) + return _u +} + +// SetNillableAsof sets the "asof" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableAsof(v *time.Time) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetAsof(*v) + } + return _u +} + +// SetMeterValue sets the "meter_value" field. +func (_u *ChargeUsageBasedRunsUpdateOne) SetMeterValue(v alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetMeterValue(v) + return _u +} + +// SetNillableMeterValue sets the "meter_value" field if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableMeterValue(v *alpacadecimal.Decimal) *ChargeUsageBasedRunsUpdateOne { + if v != nil { + _u.SetMeterValue(*v) + } + return _u +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (_u *ChargeUsageBasedRunsUpdateOne) AddCreditAllocationIDs(ids ...string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.AddCreditAllocationIDs(ids...) + return _u +} + +// AddCreditAllocations adds the "credit_allocations" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunsUpdateOne) AddCreditAllocations(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddCreditAllocationIDs(ids...) +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by ID. +func (_u *ChargeUsageBasedRunsUpdateOne) SetInvoicedUsageID(id string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetInvoicedUsageID(id) + return _u +} + +// SetNillableInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillableInvoicedUsageID(id *string) *ChargeUsageBasedRunsUpdateOne { + if id != nil { + _u = _u.SetInvoicedUsageID(*id) + } + return _u +} + +// SetInvoicedUsage sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity. +func (_u *ChargeUsageBasedRunsUpdateOne) SetInvoicedUsage(v *ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunsUpdateOne { + return _u.SetInvoicedUsageID(v.ID) +} + +// SetPaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by ID. +func (_u *ChargeUsageBasedRunsUpdateOne) SetPaymentID(id string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.SetPaymentID(id) + return _u +} + +// SetNillablePaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by ID if the given value is not nil. +func (_u *ChargeUsageBasedRunsUpdateOne) SetNillablePaymentID(id *string) *ChargeUsageBasedRunsUpdateOne { + if id != nil { + _u = _u.SetPaymentID(*id) + } + return _u +} + +// SetPayment sets the "payment" edge to the ChargeUsageBasedRunPayment entity. +func (_u *ChargeUsageBasedRunsUpdateOne) SetPayment(v *ChargeUsageBasedRunPayment) *ChargeUsageBasedRunsUpdateOne { + return _u.SetPaymentID(v.ID) +} + +// Mutation returns the ChargeUsageBasedRunsMutation object of the builder. +func (_u *ChargeUsageBasedRunsUpdateOne) Mutation() *ChargeUsageBasedRunsMutation { + return _u.mutation +} + +// ClearCreditAllocations clears all "credit_allocations" edges to the ChargeUsageBasedRunCreditAllocations entity. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearCreditAllocations() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearCreditAllocations() + return _u +} + +// RemoveCreditAllocationIDs removes the "credit_allocations" edge to ChargeUsageBasedRunCreditAllocations entities by IDs. +func (_u *ChargeUsageBasedRunsUpdateOne) RemoveCreditAllocationIDs(ids ...string) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.RemoveCreditAllocationIDs(ids...) + return _u +} + +// RemoveCreditAllocations removes "credit_allocations" edges to ChargeUsageBasedRunCreditAllocations entities. +func (_u *ChargeUsageBasedRunsUpdateOne) RemoveCreditAllocations(v ...*ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunsUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveCreditAllocationIDs(ids...) +} + +// ClearInvoicedUsage clears the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearInvoicedUsage() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearInvoicedUsage() + return _u +} + +// ClearPayment clears the "payment" edge to the ChargeUsageBasedRunPayment entity. +func (_u *ChargeUsageBasedRunsUpdateOne) ClearPayment() *ChargeUsageBasedRunsUpdateOne { + _u.mutation.ClearPayment() + return _u +} + +// Where appends a list predicates to the ChargeUsageBasedRunsUpdate builder. +func (_u *ChargeUsageBasedRunsUpdateOne) Where(ps ...predicate.ChargeUsageBasedRuns) *ChargeUsageBasedRunsUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ChargeUsageBasedRunsUpdateOne) Select(field string, fields ...string) *ChargeUsageBasedRunsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ChargeUsageBasedRuns entity. +func (_u *ChargeUsageBasedRunsUpdateOne) Save(ctx context.Context) (*ChargeUsageBasedRuns, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ChargeUsageBasedRunsUpdateOne) SaveX(ctx context.Context) *ChargeUsageBasedRuns { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ChargeUsageBasedRunsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ChargeUsageBasedRunsUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ChargeUsageBasedRunsUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := chargeusagebasedruns.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ChargeUsageBasedRunsUpdateOne) check() error { + if _u.mutation.UsageBasedCleared() && len(_u.mutation.UsageBasedIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "ChargeUsageBasedRuns.usage_based"`) + } + return nil +} + +func (_u *ChargeUsageBasedRunsUpdateOne) sqlSave(ctx context.Context) (_node *ChargeUsageBasedRuns, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(chargeusagebasedruns.Table, chargeusagebasedruns.Columns, sqlgraph.NewFieldSpec(chargeusagebasedruns.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ChargeUsageBasedRuns.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, chargeusagebasedruns.FieldID) + for _, f := range fields { + if !chargeusagebasedruns.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != chargeusagebasedruns.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(chargeusagebasedruns.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(chargeusagebasedruns.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Asof(); ok { + _spec.SetField(chargeusagebasedruns.FieldAsof, field.TypeTime, value) + } + if value, ok := _u.mutation.MeterValue(); ok { + _spec.SetField(chargeusagebasedruns.FieldMeterValue, field.TypeOther, value) + } + if _u.mutation.CreditAllocationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedCreditAllocationsIDs(); len(nodes) > 0 && !_u.mutation.CreditAllocationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.CreditAllocationsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: chargeusagebasedruns.CreditAllocationsTable, + Columns: []string{chargeusagebasedruns.CreditAllocationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruncreditallocations.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.InvoicedUsageCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.InvoicedUsageTable, + Columns: []string{chargeusagebasedruns.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InvoicedUsageIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.InvoicedUsageTable, + Columns: []string{chargeusagebasedruns.InvoicedUsageColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedruninvoicedusage.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.PaymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.PaymentTable, + Columns: []string{chargeusagebasedruns.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PaymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: chargeusagebasedruns.PaymentTable, + Columns: []string{chargeusagebasedruns.PaymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(chargeusagebasedrunpayment.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ChargeUsageBasedRuns{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{chargeusagebasedruns.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/openmeter/ent/db/client.go b/openmeter/ent/db/client.go index 73514aeea7..82fb3bdb42 100644 --- a/openmeter/ent/db/client.go +++ b/openmeter/ent/db/client.go @@ -47,6 +47,11 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeecreditallocations" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeinvoicedusage" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeepayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" @@ -146,6 +151,16 @@ type Client struct { ChargeFlatFeeInvoicedUsage *ChargeFlatFeeInvoicedUsageClient // ChargeFlatFeePayment is the client for interacting with the ChargeFlatFeePayment builders. ChargeFlatFeePayment *ChargeFlatFeePaymentClient + // ChargeUsageBased is the client for interacting with the ChargeUsageBased builders. + ChargeUsageBased *ChargeUsageBasedClient + // ChargeUsageBasedRunCreditAllocations is the client for interacting with the ChargeUsageBasedRunCreditAllocations builders. + ChargeUsageBasedRunCreditAllocations *ChargeUsageBasedRunCreditAllocationsClient + // ChargeUsageBasedRunInvoicedUsage is the client for interacting with the ChargeUsageBasedRunInvoicedUsage builders. + ChargeUsageBasedRunInvoicedUsage *ChargeUsageBasedRunInvoicedUsageClient + // ChargeUsageBasedRunPayment is the client for interacting with the ChargeUsageBasedRunPayment builders. + ChargeUsageBasedRunPayment *ChargeUsageBasedRunPaymentClient + // ChargeUsageBasedRuns is the client for interacting with the ChargeUsageBasedRuns builders. + ChargeUsageBasedRuns *ChargeUsageBasedRunsClient // CurrencyCostBasis is the client for interacting with the CurrencyCostBasis builders. CurrencyCostBasis *CurrencyCostBasisClient // CustomCurrency is the client for interacting with the CustomCurrency builders. @@ -241,6 +256,11 @@ func (c *Client) init() { c.ChargeFlatFeeCreditAllocations = NewChargeFlatFeeCreditAllocationsClient(c.config) c.ChargeFlatFeeInvoicedUsage = NewChargeFlatFeeInvoicedUsageClient(c.config) c.ChargeFlatFeePayment = NewChargeFlatFeePaymentClient(c.config) + c.ChargeUsageBased = NewChargeUsageBasedClient(c.config) + c.ChargeUsageBasedRunCreditAllocations = NewChargeUsageBasedRunCreditAllocationsClient(c.config) + c.ChargeUsageBasedRunInvoicedUsage = NewChargeUsageBasedRunInvoicedUsageClient(c.config) + c.ChargeUsageBasedRunPayment = NewChargeUsageBasedRunPaymentClient(c.config) + c.ChargeUsageBasedRuns = NewChargeUsageBasedRunsClient(c.config) c.CurrencyCostBasis = NewCurrencyCostBasisClient(c.config) c.CustomCurrency = NewCustomCurrencyClient(c.config) c.Customer = NewCustomerClient(c.config) @@ -391,6 +411,11 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ChargeFlatFeeCreditAllocations: NewChargeFlatFeeCreditAllocationsClient(cfg), ChargeFlatFeeInvoicedUsage: NewChargeFlatFeeInvoicedUsageClient(cfg), ChargeFlatFeePayment: NewChargeFlatFeePaymentClient(cfg), + ChargeUsageBased: NewChargeUsageBasedClient(cfg), + ChargeUsageBasedRunCreditAllocations: NewChargeUsageBasedRunCreditAllocationsClient(cfg), + ChargeUsageBasedRunInvoicedUsage: NewChargeUsageBasedRunInvoicedUsageClient(cfg), + ChargeUsageBasedRunPayment: NewChargeUsageBasedRunPaymentClient(cfg), + ChargeUsageBasedRuns: NewChargeUsageBasedRunsClient(cfg), CurrencyCostBasis: NewCurrencyCostBasisClient(cfg), CustomCurrency: NewCustomCurrencyClient(cfg), Customer: NewCustomerClient(cfg), @@ -468,6 +493,11 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ChargeFlatFeeCreditAllocations: NewChargeFlatFeeCreditAllocationsClient(cfg), ChargeFlatFeeInvoicedUsage: NewChargeFlatFeeInvoicedUsageClient(cfg), ChargeFlatFeePayment: NewChargeFlatFeePaymentClient(cfg), + ChargeUsageBased: NewChargeUsageBasedClient(cfg), + ChargeUsageBasedRunCreditAllocations: NewChargeUsageBasedRunCreditAllocationsClient(cfg), + ChargeUsageBasedRunInvoicedUsage: NewChargeUsageBasedRunInvoicedUsageClient(cfg), + ChargeUsageBasedRunPayment: NewChargeUsageBasedRunPaymentClient(cfg), + ChargeUsageBasedRuns: NewChargeUsageBasedRunsClient(cfg), CurrencyCostBasis: NewCurrencyCostBasisClient(cfg), CustomCurrency: NewCustomCurrencyClient(cfg), Customer: NewCustomerClient(cfg), @@ -535,7 +565,9 @@ func (c *Client) Use(hooks ...Hook) { c.BillingStandardInvoiceDetailedLineAmountDiscount, c.BillingWorkflowConfig, c.Charge, c.ChargeCreditPurchase, c.ChargeCreditPurchaseExternalPayment, c.ChargeFlatFee, c.ChargeFlatFeeCreditAllocations, - c.ChargeFlatFeeInvoicedUsage, c.ChargeFlatFeePayment, c.CurrencyCostBasis, + c.ChargeFlatFeeInvoicedUsage, c.ChargeFlatFeePayment, c.ChargeUsageBased, + c.ChargeUsageBasedRunCreditAllocations, c.ChargeUsageBasedRunInvoicedUsage, + c.ChargeUsageBasedRunPayment, c.ChargeUsageBasedRuns, c.CurrencyCostBasis, c.CustomCurrency, c.Customer, c.CustomerSubjects, c.Entitlement, c.Feature, c.Grant, c.LLMCostPrice, c.Meter, c.NotificationChannel, c.NotificationEvent, c.NotificationEventDeliveryStatus, c.NotificationRule, c.Plan, c.PlanAddon, @@ -563,7 +595,9 @@ func (c *Client) Intercept(interceptors ...Interceptor) { c.BillingStandardInvoiceDetailedLineAmountDiscount, c.BillingWorkflowConfig, c.Charge, c.ChargeCreditPurchase, c.ChargeCreditPurchaseExternalPayment, c.ChargeFlatFee, c.ChargeFlatFeeCreditAllocations, - c.ChargeFlatFeeInvoicedUsage, c.ChargeFlatFeePayment, c.CurrencyCostBasis, + c.ChargeFlatFeeInvoicedUsage, c.ChargeFlatFeePayment, c.ChargeUsageBased, + c.ChargeUsageBasedRunCreditAllocations, c.ChargeUsageBasedRunInvoicedUsage, + c.ChargeUsageBasedRunPayment, c.ChargeUsageBasedRuns, c.CurrencyCostBasis, c.CustomCurrency, c.Customer, c.CustomerSubjects, c.Entitlement, c.Feature, c.Grant, c.LLMCostPrice, c.Meter, c.NotificationChannel, c.NotificationEvent, c.NotificationEventDeliveryStatus, c.NotificationRule, c.Plan, c.PlanAddon, @@ -642,6 +676,16 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.ChargeFlatFeeInvoicedUsage.mutate(ctx, m) case *ChargeFlatFeePaymentMutation: return c.ChargeFlatFeePayment.mutate(ctx, m) + case *ChargeUsageBasedMutation: + return c.ChargeUsageBased.mutate(ctx, m) + case *ChargeUsageBasedRunCreditAllocationsMutation: + return c.ChargeUsageBasedRunCreditAllocations.mutate(ctx, m) + case *ChargeUsageBasedRunInvoicedUsageMutation: + return c.ChargeUsageBasedRunInvoicedUsage.mutate(ctx, m) + case *ChargeUsageBasedRunPaymentMutation: + return c.ChargeUsageBasedRunPayment.mutate(ctx, m) + case *ChargeUsageBasedRunsMutation: + return c.ChargeUsageBasedRuns.mutate(ctx, m) case *CurrencyCostBasisMutation: return c.CurrencyCostBasis.mutate(ctx, m) case *CustomCurrencyMutation: @@ -5284,6 +5328,22 @@ func (c *ChargeClient) QueryCreditPurchase(_m *Charge) *ChargeCreditPurchaseQuer return query } +// QueryUsageBased queries the usage_based edge of a Charge. +func (c *ChargeClient) QueryUsageBased(_m *Charge) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(charge.Table, charge.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, charge.UsageBasedTable, charge.UsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryBillingInvoiceLines queries the billing_invoice_lines edge of a Charge. func (c *ChargeClient) QueryBillingInvoiceLines(_m *Charge) *BillingInvoiceLineQuery { query := (&BillingInvoiceLineClient{config: c.config}).Query() @@ -6411,6 +6471,815 @@ func (c *ChargeFlatFeePaymentClient) mutate(ctx context.Context, m *ChargeFlatFe } } +// ChargeUsageBasedClient is a client for the ChargeUsageBased schema. +type ChargeUsageBasedClient struct { + config +} + +// NewChargeUsageBasedClient returns a client for the ChargeUsageBased from the given config. +func NewChargeUsageBasedClient(c config) *ChargeUsageBasedClient { + return &ChargeUsageBasedClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebased.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBased = append(c.hooks.ChargeUsageBased, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebased.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBased = append(c.inters.ChargeUsageBased, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBased entity. +func (c *ChargeUsageBasedClient) Create() *ChargeUsageBasedCreate { + mutation := newChargeUsageBasedMutation(c.config, OpCreate) + return &ChargeUsageBasedCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBased entities. +func (c *ChargeUsageBasedClient) CreateBulk(builders ...*ChargeUsageBasedCreate) *ChargeUsageBasedCreateBulk { + return &ChargeUsageBasedCreateBulk{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 *ChargeUsageBasedClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedCreate, int)) *ChargeUsageBasedCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBased. +func (c *ChargeUsageBasedClient) Update() *ChargeUsageBasedUpdate { + mutation := newChargeUsageBasedMutation(c.config, OpUpdate) + return &ChargeUsageBasedUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedClient) UpdateOne(_m *ChargeUsageBased) *ChargeUsageBasedUpdateOne { + mutation := newChargeUsageBasedMutation(c.config, OpUpdateOne, withChargeUsageBased(_m)) + return &ChargeUsageBasedUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedClient) UpdateOneID(id string) *ChargeUsageBasedUpdateOne { + mutation := newChargeUsageBasedMutation(c.config, OpUpdateOne, withChargeUsageBasedID(id)) + return &ChargeUsageBasedUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBased. +func (c *ChargeUsageBasedClient) Delete() *ChargeUsageBasedDelete { + mutation := newChargeUsageBasedMutation(c.config, OpDelete) + return &ChargeUsageBasedDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedClient) DeleteOne(_m *ChargeUsageBased) *ChargeUsageBasedDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedClient) DeleteOneID(id string) *ChargeUsageBasedDeleteOne { + builder := c.Delete().Where(chargeusagebased.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBased. +func (c *ChargeUsageBasedClient) Query() *ChargeUsageBasedQuery { + return &ChargeUsageBasedQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBased}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBased entity by its id. +func (c *ChargeUsageBasedClient) Get(ctx context.Context, id string) (*ChargeUsageBased, error) { + return c.Query().Where(chargeusagebased.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedClient) GetX(ctx context.Context, id string) *ChargeUsageBased { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryCharge queries the charge edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryCharge(_m *ChargeUsageBased) *ChargeQuery { + query := (&ChargeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebased.Table, chargeusagebased.FieldID, id), + sqlgraph.To(charge.Table, charge.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebased.ChargeTable, chargeusagebased.ChargeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRuns queries the runs edge of a ChargeUsageBased. +func (c *ChargeUsageBasedClient) QueryRuns(_m *ChargeUsageBased) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebased.Table, chargeusagebased.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebased.RunsTable, chargeusagebased.RunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedClient) Hooks() []Hook { + return c.hooks.ChargeUsageBased +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBased +} + +func (c *ChargeUsageBasedClient) mutate(ctx context.Context, m *ChargeUsageBasedMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBased mutation op: %q", m.Op()) + } +} + +// ChargeUsageBasedRunCreditAllocationsClient is a client for the ChargeUsageBasedRunCreditAllocations schema. +type ChargeUsageBasedRunCreditAllocationsClient struct { + config +} + +// NewChargeUsageBasedRunCreditAllocationsClient returns a client for the ChargeUsageBasedRunCreditAllocations from the given config. +func NewChargeUsageBasedRunCreditAllocationsClient(c config) *ChargeUsageBasedRunCreditAllocationsClient { + return &ChargeUsageBasedRunCreditAllocationsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebasedruncreditallocations.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBasedRunCreditAllocations = append(c.hooks.ChargeUsageBasedRunCreditAllocations, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebasedruncreditallocations.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBasedRunCreditAllocations = append(c.inters.ChargeUsageBasedRunCreditAllocations, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBasedRunCreditAllocations entity. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Create() *ChargeUsageBasedRunCreditAllocationsCreate { + mutation := newChargeUsageBasedRunCreditAllocationsMutation(c.config, OpCreate) + return &ChargeUsageBasedRunCreditAllocationsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBasedRunCreditAllocations entities. +func (c *ChargeUsageBasedRunCreditAllocationsClient) CreateBulk(builders ...*ChargeUsageBasedRunCreditAllocationsCreate) *ChargeUsageBasedRunCreditAllocationsCreateBulk { + return &ChargeUsageBasedRunCreditAllocationsCreateBulk{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 *ChargeUsageBasedRunCreditAllocationsClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedRunCreditAllocationsCreate, int)) *ChargeUsageBasedRunCreditAllocationsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedRunCreditAllocationsCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedRunCreditAllocationsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedRunCreditAllocationsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedRunCreditAllocationsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBasedRunCreditAllocations. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Update() *ChargeUsageBasedRunCreditAllocationsUpdate { + mutation := newChargeUsageBasedRunCreditAllocationsMutation(c.config, OpUpdate) + return &ChargeUsageBasedRunCreditAllocationsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedRunCreditAllocationsClient) UpdateOne(_m *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + mutation := newChargeUsageBasedRunCreditAllocationsMutation(c.config, OpUpdateOne, withChargeUsageBasedRunCreditAllocations(_m)) + return &ChargeUsageBasedRunCreditAllocationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedRunCreditAllocationsClient) UpdateOneID(id string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + mutation := newChargeUsageBasedRunCreditAllocationsMutation(c.config, OpUpdateOne, withChargeUsageBasedRunCreditAllocationsID(id)) + return &ChargeUsageBasedRunCreditAllocationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBasedRunCreditAllocations. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Delete() *ChargeUsageBasedRunCreditAllocationsDelete { + mutation := newChargeUsageBasedRunCreditAllocationsMutation(c.config, OpDelete) + return &ChargeUsageBasedRunCreditAllocationsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedRunCreditAllocationsClient) DeleteOne(_m *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunCreditAllocationsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedRunCreditAllocationsClient) DeleteOneID(id string) *ChargeUsageBasedRunCreditAllocationsDeleteOne { + builder := c.Delete().Where(chargeusagebasedruncreditallocations.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedRunCreditAllocationsDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBasedRunCreditAllocations. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Query() *ChargeUsageBasedRunCreditAllocationsQuery { + return &ChargeUsageBasedRunCreditAllocationsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBasedRunCreditAllocations}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBasedRunCreditAllocations entity by its id. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Get(ctx context.Context, id string) (*ChargeUsageBasedRunCreditAllocations, error) { + return c.Query().Where(chargeusagebasedruncreditallocations.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedRunCreditAllocationsClient) GetX(ctx context.Context, id string) *ChargeUsageBasedRunCreditAllocations { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRun queries the run edge of a ChargeUsageBasedRunCreditAllocations. +func (c *ChargeUsageBasedRunCreditAllocationsClient) QueryRun(_m *ChargeUsageBasedRunCreditAllocations) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruncreditallocations.RunTable, chargeusagebasedruncreditallocations.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Hooks() []Hook { + return c.hooks.ChargeUsageBasedRunCreditAllocations +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedRunCreditAllocationsClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBasedRunCreditAllocations +} + +func (c *ChargeUsageBasedRunCreditAllocationsClient) mutate(ctx context.Context, m *ChargeUsageBasedRunCreditAllocationsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedRunCreditAllocationsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedRunCreditAllocationsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedRunCreditAllocationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedRunCreditAllocationsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBasedRunCreditAllocations mutation op: %q", m.Op()) + } +} + +// ChargeUsageBasedRunInvoicedUsageClient is a client for the ChargeUsageBasedRunInvoicedUsage schema. +type ChargeUsageBasedRunInvoicedUsageClient struct { + config +} + +// NewChargeUsageBasedRunInvoicedUsageClient returns a client for the ChargeUsageBasedRunInvoicedUsage from the given config. +func NewChargeUsageBasedRunInvoicedUsageClient(c config) *ChargeUsageBasedRunInvoicedUsageClient { + return &ChargeUsageBasedRunInvoicedUsageClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebasedruninvoicedusage.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBasedRunInvoicedUsage = append(c.hooks.ChargeUsageBasedRunInvoicedUsage, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebasedruninvoicedusage.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBasedRunInvoicedUsage = append(c.inters.ChargeUsageBasedRunInvoicedUsage, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBasedRunInvoicedUsage entity. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Create() *ChargeUsageBasedRunInvoicedUsageCreate { + mutation := newChargeUsageBasedRunInvoicedUsageMutation(c.config, OpCreate) + return &ChargeUsageBasedRunInvoicedUsageCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBasedRunInvoicedUsage entities. +func (c *ChargeUsageBasedRunInvoicedUsageClient) CreateBulk(builders ...*ChargeUsageBasedRunInvoicedUsageCreate) *ChargeUsageBasedRunInvoicedUsageCreateBulk { + return &ChargeUsageBasedRunInvoicedUsageCreateBulk{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 *ChargeUsageBasedRunInvoicedUsageClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedRunInvoicedUsageCreate, int)) *ChargeUsageBasedRunInvoicedUsageCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedRunInvoicedUsageCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedRunInvoicedUsageClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedRunInvoicedUsageCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedRunInvoicedUsageCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBasedRunInvoicedUsage. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Update() *ChargeUsageBasedRunInvoicedUsageUpdate { + mutation := newChargeUsageBasedRunInvoicedUsageMutation(c.config, OpUpdate) + return &ChargeUsageBasedRunInvoicedUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedRunInvoicedUsageClient) UpdateOne(_m *ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + mutation := newChargeUsageBasedRunInvoicedUsageMutation(c.config, OpUpdateOne, withChargeUsageBasedRunInvoicedUsage(_m)) + return &ChargeUsageBasedRunInvoicedUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedRunInvoicedUsageClient) UpdateOneID(id string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + mutation := newChargeUsageBasedRunInvoicedUsageMutation(c.config, OpUpdateOne, withChargeUsageBasedRunInvoicedUsageID(id)) + return &ChargeUsageBasedRunInvoicedUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBasedRunInvoicedUsage. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Delete() *ChargeUsageBasedRunInvoicedUsageDelete { + mutation := newChargeUsageBasedRunInvoicedUsageMutation(c.config, OpDelete) + return &ChargeUsageBasedRunInvoicedUsageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedRunInvoicedUsageClient) DeleteOne(_m *ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunInvoicedUsageDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedRunInvoicedUsageClient) DeleteOneID(id string) *ChargeUsageBasedRunInvoicedUsageDeleteOne { + builder := c.Delete().Where(chargeusagebasedruninvoicedusage.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedRunInvoicedUsageDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBasedRunInvoicedUsage. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Query() *ChargeUsageBasedRunInvoicedUsageQuery { + return &ChargeUsageBasedRunInvoicedUsageQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBasedRunInvoicedUsage}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBasedRunInvoicedUsage entity by its id. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Get(ctx context.Context, id string) (*ChargeUsageBasedRunInvoicedUsage, error) { + return c.Query().Where(chargeusagebasedruninvoicedusage.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedRunInvoicedUsageClient) GetX(ctx context.Context, id string) *ChargeUsageBasedRunInvoicedUsage { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRun queries the run edge of a ChargeUsageBasedRunInvoicedUsage. +func (c *ChargeUsageBasedRunInvoicedUsageClient) QueryRun(_m *ChargeUsageBasedRunInvoicedUsage) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedruninvoicedusage.RunTable, chargeusagebasedruninvoicedusage.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Hooks() []Hook { + return c.hooks.ChargeUsageBasedRunInvoicedUsage +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedRunInvoicedUsageClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBasedRunInvoicedUsage +} + +func (c *ChargeUsageBasedRunInvoicedUsageClient) mutate(ctx context.Context, m *ChargeUsageBasedRunInvoicedUsageMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedRunInvoicedUsageCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedRunInvoicedUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedRunInvoicedUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedRunInvoicedUsageDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBasedRunInvoicedUsage mutation op: %q", m.Op()) + } +} + +// ChargeUsageBasedRunPaymentClient is a client for the ChargeUsageBasedRunPayment schema. +type ChargeUsageBasedRunPaymentClient struct { + config +} + +// NewChargeUsageBasedRunPaymentClient returns a client for the ChargeUsageBasedRunPayment from the given config. +func NewChargeUsageBasedRunPaymentClient(c config) *ChargeUsageBasedRunPaymentClient { + return &ChargeUsageBasedRunPaymentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebasedrunpayment.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedRunPaymentClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBasedRunPayment = append(c.hooks.ChargeUsageBasedRunPayment, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebasedrunpayment.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedRunPaymentClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBasedRunPayment = append(c.inters.ChargeUsageBasedRunPayment, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBasedRunPayment entity. +func (c *ChargeUsageBasedRunPaymentClient) Create() *ChargeUsageBasedRunPaymentCreate { + mutation := newChargeUsageBasedRunPaymentMutation(c.config, OpCreate) + return &ChargeUsageBasedRunPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBasedRunPayment entities. +func (c *ChargeUsageBasedRunPaymentClient) CreateBulk(builders ...*ChargeUsageBasedRunPaymentCreate) *ChargeUsageBasedRunPaymentCreateBulk { + return &ChargeUsageBasedRunPaymentCreateBulk{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 *ChargeUsageBasedRunPaymentClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedRunPaymentCreate, int)) *ChargeUsageBasedRunPaymentCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedRunPaymentCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedRunPaymentClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedRunPaymentCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedRunPaymentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBasedRunPayment. +func (c *ChargeUsageBasedRunPaymentClient) Update() *ChargeUsageBasedRunPaymentUpdate { + mutation := newChargeUsageBasedRunPaymentMutation(c.config, OpUpdate) + return &ChargeUsageBasedRunPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedRunPaymentClient) UpdateOne(_m *ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentUpdateOne { + mutation := newChargeUsageBasedRunPaymentMutation(c.config, OpUpdateOne, withChargeUsageBasedRunPayment(_m)) + return &ChargeUsageBasedRunPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedRunPaymentClient) UpdateOneID(id string) *ChargeUsageBasedRunPaymentUpdateOne { + mutation := newChargeUsageBasedRunPaymentMutation(c.config, OpUpdateOne, withChargeUsageBasedRunPaymentID(id)) + return &ChargeUsageBasedRunPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBasedRunPayment. +func (c *ChargeUsageBasedRunPaymentClient) Delete() *ChargeUsageBasedRunPaymentDelete { + mutation := newChargeUsageBasedRunPaymentMutation(c.config, OpDelete) + return &ChargeUsageBasedRunPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedRunPaymentClient) DeleteOne(_m *ChargeUsageBasedRunPayment) *ChargeUsageBasedRunPaymentDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedRunPaymentClient) DeleteOneID(id string) *ChargeUsageBasedRunPaymentDeleteOne { + builder := c.Delete().Where(chargeusagebasedrunpayment.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedRunPaymentDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBasedRunPayment. +func (c *ChargeUsageBasedRunPaymentClient) Query() *ChargeUsageBasedRunPaymentQuery { + return &ChargeUsageBasedRunPaymentQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBasedRunPayment}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBasedRunPayment entity by its id. +func (c *ChargeUsageBasedRunPaymentClient) Get(ctx context.Context, id string) (*ChargeUsageBasedRunPayment, error) { + return c.Query().Where(chargeusagebasedrunpayment.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedRunPaymentClient) GetX(ctx context.Context, id string) *ChargeUsageBasedRunPayment { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRun queries the run edge of a ChargeUsageBasedRunPayment. +func (c *ChargeUsageBasedRunPaymentClient) QueryRun(_m *ChargeUsageBasedRunPayment) *ChargeUsageBasedRunsQuery { + query := (&ChargeUsageBasedRunsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.FieldID, id), + sqlgraph.To(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, chargeusagebasedrunpayment.RunTable, chargeusagebasedrunpayment.RunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedRunPaymentClient) Hooks() []Hook { + return c.hooks.ChargeUsageBasedRunPayment +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedRunPaymentClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBasedRunPayment +} + +func (c *ChargeUsageBasedRunPaymentClient) mutate(ctx context.Context, m *ChargeUsageBasedRunPaymentMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedRunPaymentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedRunPaymentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedRunPaymentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedRunPaymentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBasedRunPayment mutation op: %q", m.Op()) + } +} + +// ChargeUsageBasedRunsClient is a client for the ChargeUsageBasedRuns schema. +type ChargeUsageBasedRunsClient struct { + config +} + +// NewChargeUsageBasedRunsClient returns a client for the ChargeUsageBasedRuns from the given config. +func NewChargeUsageBasedRunsClient(c config) *ChargeUsageBasedRunsClient { + return &ChargeUsageBasedRunsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `chargeusagebasedruns.Hooks(f(g(h())))`. +func (c *ChargeUsageBasedRunsClient) Use(hooks ...Hook) { + c.hooks.ChargeUsageBasedRuns = append(c.hooks.ChargeUsageBasedRuns, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `chargeusagebasedruns.Intercept(f(g(h())))`. +func (c *ChargeUsageBasedRunsClient) Intercept(interceptors ...Interceptor) { + c.inters.ChargeUsageBasedRuns = append(c.inters.ChargeUsageBasedRuns, interceptors...) +} + +// Create returns a builder for creating a ChargeUsageBasedRuns entity. +func (c *ChargeUsageBasedRunsClient) Create() *ChargeUsageBasedRunsCreate { + mutation := newChargeUsageBasedRunsMutation(c.config, OpCreate) + return &ChargeUsageBasedRunsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ChargeUsageBasedRuns entities. +func (c *ChargeUsageBasedRunsClient) CreateBulk(builders ...*ChargeUsageBasedRunsCreate) *ChargeUsageBasedRunsCreateBulk { + return &ChargeUsageBasedRunsCreateBulk{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 *ChargeUsageBasedRunsClient) MapCreateBulk(slice any, setFunc func(*ChargeUsageBasedRunsCreate, int)) *ChargeUsageBasedRunsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ChargeUsageBasedRunsCreateBulk{err: fmt.Errorf("calling to ChargeUsageBasedRunsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ChargeUsageBasedRunsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ChargeUsageBasedRunsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) Update() *ChargeUsageBasedRunsUpdate { + mutation := newChargeUsageBasedRunsMutation(c.config, OpUpdate) + return &ChargeUsageBasedRunsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ChargeUsageBasedRunsClient) UpdateOne(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunsUpdateOne { + mutation := newChargeUsageBasedRunsMutation(c.config, OpUpdateOne, withChargeUsageBasedRuns(_m)) + return &ChargeUsageBasedRunsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ChargeUsageBasedRunsClient) UpdateOneID(id string) *ChargeUsageBasedRunsUpdateOne { + mutation := newChargeUsageBasedRunsMutation(c.config, OpUpdateOne, withChargeUsageBasedRunsID(id)) + return &ChargeUsageBasedRunsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) Delete() *ChargeUsageBasedRunsDelete { + mutation := newChargeUsageBasedRunsMutation(c.config, OpDelete) + return &ChargeUsageBasedRunsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ChargeUsageBasedRunsClient) DeleteOne(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ChargeUsageBasedRunsClient) DeleteOneID(id string) *ChargeUsageBasedRunsDeleteOne { + builder := c.Delete().Where(chargeusagebasedruns.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ChargeUsageBasedRunsDeleteOne{builder} +} + +// Query returns a query builder for ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) Query() *ChargeUsageBasedRunsQuery { + return &ChargeUsageBasedRunsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeChargeUsageBasedRuns}, + inters: c.Interceptors(), + } +} + +// Get returns a ChargeUsageBasedRuns entity by its id. +func (c *ChargeUsageBasedRunsClient) Get(ctx context.Context, id string) (*ChargeUsageBasedRuns, error) { + return c.Query().Where(chargeusagebasedruns.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ChargeUsageBasedRunsClient) GetX(ctx context.Context, id string) *ChargeUsageBasedRuns { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUsageBased queries the usage_based edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryUsageBased(_m *ChargeUsageBasedRuns) *ChargeUsageBasedQuery { + query := (&ChargeUsageBasedClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, id), + sqlgraph.To(chargeusagebased.Table, chargeusagebased.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, chargeusagebasedruns.UsageBasedTable, chargeusagebasedruns.UsageBasedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCreditAllocations queries the credit_allocations edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryCreditAllocations(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunCreditAllocationsQuery { + query := (&ChargeUsageBasedRunCreditAllocationsClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, id), + sqlgraph.To(chargeusagebasedruncreditallocations.Table, chargeusagebasedruncreditallocations.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, chargeusagebasedruns.CreditAllocationsTable, chargeusagebasedruns.CreditAllocationsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryInvoicedUsage queries the invoiced_usage edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryInvoicedUsage(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunInvoicedUsageQuery { + query := (&ChargeUsageBasedRunInvoicedUsageClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, id), + sqlgraph.To(chargeusagebasedruninvoicedusage.Table, chargeusagebasedruninvoicedusage.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeusagebasedruns.InvoicedUsageTable, chargeusagebasedruns.InvoicedUsageColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryPayment queries the payment edge of a ChargeUsageBasedRuns. +func (c *ChargeUsageBasedRunsClient) QueryPayment(_m *ChargeUsageBasedRuns) *ChargeUsageBasedRunPaymentQuery { + query := (&ChargeUsageBasedRunPaymentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(chargeusagebasedruns.Table, chargeusagebasedruns.FieldID, id), + sqlgraph.To(chargeusagebasedrunpayment.Table, chargeusagebasedrunpayment.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, chargeusagebasedruns.PaymentTable, chargeusagebasedruns.PaymentColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ChargeUsageBasedRunsClient) Hooks() []Hook { + return c.hooks.ChargeUsageBasedRuns +} + +// Interceptors returns the client interceptors. +func (c *ChargeUsageBasedRunsClient) Interceptors() []Interceptor { + return c.inters.ChargeUsageBasedRuns +} + +func (c *ChargeUsageBasedRunsClient) mutate(ctx context.Context, m *ChargeUsageBasedRunsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ChargeUsageBasedRunsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ChargeUsageBasedRunsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ChargeUsageBasedRunsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ChargeUsageBasedRunsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown ChargeUsageBasedRuns mutation op: %q", m.Op()) + } +} + // CurrencyCostBasisClient is a client for the CurrencyCostBasis schema. type CurrencyCostBasisClient struct { config @@ -10827,7 +11696,9 @@ type ( BillingStandardInvoiceDetailedLineAmountDiscount, BillingWorkflowConfig, Charge, ChargeCreditPurchase, ChargeCreditPurchaseExternalPayment, ChargeFlatFee, ChargeFlatFeeCreditAllocations, ChargeFlatFeeInvoicedUsage, - ChargeFlatFeePayment, CurrencyCostBasis, CustomCurrency, Customer, + ChargeFlatFeePayment, ChargeUsageBased, ChargeUsageBasedRunCreditAllocations, + ChargeUsageBasedRunInvoicedUsage, ChargeUsageBasedRunPayment, + ChargeUsageBasedRuns, CurrencyCostBasis, CustomCurrency, Customer, CustomerSubjects, Entitlement, Feature, Grant, LLMCostPrice, Meter, NotificationChannel, NotificationEvent, NotificationEventDeliveryStatus, NotificationRule, Plan, PlanAddon, PlanPhase, PlanRateCard, Subject, @@ -10847,7 +11718,9 @@ type ( BillingStandardInvoiceDetailedLineAmountDiscount, BillingWorkflowConfig, Charge, ChargeCreditPurchase, ChargeCreditPurchaseExternalPayment, ChargeFlatFee, ChargeFlatFeeCreditAllocations, ChargeFlatFeeInvoicedUsage, - ChargeFlatFeePayment, CurrencyCostBasis, CustomCurrency, Customer, + ChargeFlatFeePayment, ChargeUsageBased, ChargeUsageBasedRunCreditAllocations, + ChargeUsageBasedRunInvoicedUsage, ChargeUsageBasedRunPayment, + ChargeUsageBasedRuns, CurrencyCostBasis, CustomCurrency, Customer, CustomerSubjects, Entitlement, Feature, Grant, LLMCostPrice, Meter, NotificationChannel, NotificationEvent, NotificationEventDeliveryStatus, NotificationRule, Plan, PlanAddon, PlanPhase, PlanRateCard, Subject, diff --git a/openmeter/ent/db/ent.go b/openmeter/ent/db/ent.go index c3b3b3f06f..aedbd9b70b 100644 --- a/openmeter/ent/db/ent.go +++ b/openmeter/ent/db/ent.go @@ -45,6 +45,11 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeecreditallocations" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeinvoicedusage" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeepayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" @@ -167,6 +172,11 @@ func checkColumn(t, c string) error { chargeflatfeecreditallocations.Table: chargeflatfeecreditallocations.ValidColumn, chargeflatfeeinvoicedusage.Table: chargeflatfeeinvoicedusage.ValidColumn, chargeflatfeepayment.Table: chargeflatfeepayment.ValidColumn, + chargeusagebased.Table: chargeusagebased.ValidColumn, + chargeusagebasedruncreditallocations.Table: chargeusagebasedruncreditallocations.ValidColumn, + chargeusagebasedruninvoicedusage.Table: chargeusagebasedruninvoicedusage.ValidColumn, + chargeusagebasedrunpayment.Table: chargeusagebasedrunpayment.ValidColumn, + chargeusagebasedruns.Table: chargeusagebasedruns.ValidColumn, currencycostbasis.Table: currencycostbasis.ValidColumn, customcurrency.Table: customcurrency.ValidColumn, customer.Table: customer.ValidColumn, diff --git a/openmeter/ent/db/entmixinaccessor.go b/openmeter/ent/db/entmixinaccessor.go index a347480369..1319a14d0b 100644 --- a/openmeter/ent/db/entmixinaccessor.go +++ b/openmeter/ent/db/entmixinaccessor.go @@ -1085,6 +1085,214 @@ func (e *ChargeFlatFeePayment) GetAnnotations() models.Annotations { return e.Annotations } +func (e *ChargeUsageBased) GetID() string { + return e.ID +} + +func (e *ChargeUsageBased) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetLineID() *string { + return e.LineID +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetLedgerTransactionGroupID() string { + return e.LedgerTransactionGroupID +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeUsageBasedRunCreditAllocations) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetLineID() *string { + return e.LineID +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetMutable() bool { + return e.Mutable +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetLedgerTransactionGroupID() *string { + return e.LedgerTransactionGroupID +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetTaxesTotal() alpacadecimal.Decimal { + return e.TaxesTotal +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetTaxesInclusiveTotal() alpacadecimal.Decimal { + return e.TaxesInclusiveTotal +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetTaxesExclusiveTotal() alpacadecimal.Decimal { + return e.TaxesExclusiveTotal +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetChargesTotal() alpacadecimal.Decimal { + return e.ChargesTotal +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetDiscountsTotal() alpacadecimal.Decimal { + return e.DiscountsTotal +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetCreditsTotal() alpacadecimal.Decimal { + return e.CreditsTotal +} + +func (e *ChargeUsageBasedRunInvoicedUsage) GetTotal() alpacadecimal.Decimal { + return e.Total +} + +func (e *ChargeUsageBasedRunPayment) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedRunPayment) GetLineID() string { + return e.LineID +} + +func (e *ChargeUsageBasedRunPayment) GetServicePeriodFrom() time.Time { + return e.ServicePeriodFrom +} + +func (e *ChargeUsageBasedRunPayment) GetServicePeriodTo() time.Time { + return e.ServicePeriodTo +} + +func (e *ChargeUsageBasedRunPayment) GetStatus() payment.Status { + return e.Status +} + +func (e *ChargeUsageBasedRunPayment) GetAmount() alpacadecimal.Decimal { + return e.Amount +} + +func (e *ChargeUsageBasedRunPayment) GetAuthorizedTransactionGroupID() *string { + return e.AuthorizedTransactionGroupID +} + +func (e *ChargeUsageBasedRunPayment) GetAuthorizedAt() *time.Time { + return e.AuthorizedAt +} + +func (e *ChargeUsageBasedRunPayment) GetSettledTransactionGroupID() *string { + return e.SettledTransactionGroupID +} + +func (e *ChargeUsageBasedRunPayment) GetSettledAt() *time.Time { + return e.SettledAt +} + +func (e *ChargeUsageBasedRunPayment) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBasedRunPayment) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeUsageBasedRunPayment) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeUsageBasedRunPayment) GetDeletedAt() *time.Time { + return e.DeletedAt +} + +func (e *ChargeUsageBasedRunPayment) GetAnnotations() models.Annotations { + return e.Annotations +} + +func (e *ChargeUsageBasedRuns) GetID() string { + return e.ID +} + +func (e *ChargeUsageBasedRuns) GetNamespace() string { + return e.Namespace +} + +func (e *ChargeUsageBasedRuns) GetCreatedAt() time.Time { + return e.CreatedAt +} + +func (e *ChargeUsageBasedRuns) GetUpdatedAt() time.Time { + return e.UpdatedAt +} + +func (e *ChargeUsageBasedRuns) GetDeletedAt() *time.Time { + return e.DeletedAt +} + func (e *CurrencyCostBasis) GetID() string { return e.ID } diff --git a/openmeter/ent/db/expose.go b/openmeter/ent/db/expose.go index 70b6c677ee..bf7d239b84 100644 --- a/openmeter/ent/db/expose.go +++ b/openmeter/ent/db/expose.go @@ -153,6 +153,16 @@ func NewTxClientFromRawConfig(ctx context.Context, cfg entutils.RawEntConfig) *T ChargeFlatFeePayment: NewChargeFlatFeePaymentClient(config), + ChargeUsageBased: NewChargeUsageBasedClient(config), + + ChargeUsageBasedRunCreditAllocations: NewChargeUsageBasedRunCreditAllocationsClient(config), + + ChargeUsageBasedRunInvoicedUsage: NewChargeUsageBasedRunInvoicedUsageClient(config), + + ChargeUsageBasedRunPayment: NewChargeUsageBasedRunPaymentClient(config), + + ChargeUsageBasedRuns: NewChargeUsageBasedRunsClient(config), + CurrencyCostBasis: NewCurrencyCostBasisClient(config), CustomCurrency: NewCustomCurrencyClient(config), diff --git a/openmeter/ent/db/hook/hook.go b/openmeter/ent/db/hook/hook.go index 375917c1f5..d7a4ee43e9 100644 --- a/openmeter/ent/db/hook/hook.go +++ b/openmeter/ent/db/hook/hook.go @@ -393,6 +393,66 @@ func (f ChargeFlatFeePaymentFunc) Mutate(ctx context.Context, m db.Mutation) (db return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeFlatFeePaymentMutation", m) } +// The ChargeUsageBasedFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBased mutator. +type ChargeUsageBasedFunc func(context.Context, *db.ChargeUsageBasedMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedMutation", m) +} + +// The ChargeUsageBasedRunCreditAllocationsFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBasedRunCreditAllocations mutator. +type ChargeUsageBasedRunCreditAllocationsFunc func(context.Context, *db.ChargeUsageBasedRunCreditAllocationsMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedRunCreditAllocationsFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedRunCreditAllocationsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedRunCreditAllocationsMutation", m) +} + +// The ChargeUsageBasedRunInvoicedUsageFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBasedRunInvoicedUsage mutator. +type ChargeUsageBasedRunInvoicedUsageFunc func(context.Context, *db.ChargeUsageBasedRunInvoicedUsageMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedRunInvoicedUsageFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedRunInvoicedUsageMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedRunInvoicedUsageMutation", m) +} + +// The ChargeUsageBasedRunPaymentFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBasedRunPayment mutator. +type ChargeUsageBasedRunPaymentFunc func(context.Context, *db.ChargeUsageBasedRunPaymentMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedRunPaymentFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedRunPaymentMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedRunPaymentMutation", m) +} + +// The ChargeUsageBasedRunsFunc type is an adapter to allow the use of ordinary +// function as ChargeUsageBasedRuns mutator. +type ChargeUsageBasedRunsFunc func(context.Context, *db.ChargeUsageBasedRunsMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ChargeUsageBasedRunsFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ChargeUsageBasedRunsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ChargeUsageBasedRunsMutation", m) +} + // The CurrencyCostBasisFunc type is an adapter to allow the use of ordinary // function as CurrencyCostBasis mutator. type CurrencyCostBasisFunc func(context.Context, *db.CurrencyCostBasisMutation) (db.Value, error) diff --git a/openmeter/ent/db/migrate/schema.go b/openmeter/ent/db/migrate/schema.go index 0c1dd480c7..f82a36e53a 100644 --- a/openmeter/ent/db/migrate/schema.go +++ b/openmeter/ent/db/migrate/schema.go @@ -780,6 +780,7 @@ var ( {Name: "child_unique_reference_id", Type: field.TypeString, Nullable: true}, {Name: "subscription_billing_period_from", Type: field.TypeTime, Nullable: true}, {Name: "subscription_billing_period_to", Type: field.TypeTime, Nullable: true}, + {Name: "lifecycle_handler", Type: field.TypeEnum, Enums: []string{"default", "charges"}, Default: "default"}, {Name: "line_ids", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, {Name: "credits_applied", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, {Name: "invoice_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, @@ -800,55 +801,55 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "billing_invoice_lines_billing_invoices_billing_invoice_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[33]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[34]}, RefColumns: []*schema.Column{BillingInvoicesColumns[0]}, OnDelete: schema.Cascade, }, { Symbol: "billing_invoice_lines_billing_invoice_flat_fee_line_configs_flat_fee_line", - Columns: []*schema.Column{BillingInvoiceLinesColumns[34]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[35]}, RefColumns: []*schema.Column{BillingInvoiceFlatFeeLineConfigsColumns[0]}, OnDelete: schema.Cascade, }, { Symbol: "billing_invoice_lines_billing_invoice_usage_based_line_configs_usage_based_line", - Columns: []*schema.Column{BillingInvoiceLinesColumns[35]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[36]}, RefColumns: []*schema.Column{BillingInvoiceUsageBasedLineConfigsColumns[0]}, OnDelete: schema.Cascade, }, { Symbol: "billing_invoice_lines_billing_invoice_lines_detailed_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[36]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[37]}, RefColumns: []*schema.Column{BillingInvoiceLinesColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "billing_invoice_lines_billing_invoice_split_line_groups_billing_invoice_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[37]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[38]}, RefColumns: []*schema.Column{BillingInvoiceSplitLineGroupsColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "billing_invoice_lines_charges_billing_invoice_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[38]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[39]}, RefColumns: []*schema.Column{ChargesColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "billing_invoice_lines_subscriptions_billing_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[39]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[40]}, RefColumns: []*schema.Column{SubscriptionsColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "billing_invoice_lines_subscription_items_billing_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[40]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[41]}, RefColumns: []*schema.Column{SubscriptionItemsColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "billing_invoice_lines_subscription_phases_billing_lines", - Columns: []*schema.Column{BillingInvoiceLinesColumns[41]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[42]}, RefColumns: []*schema.Column{SubscriptionPhasesColumns[0]}, OnDelete: schema.SetNull, }, @@ -882,17 +883,17 @@ var ( { Name: "billinginvoiceline_namespace_invoice_id", Unique: false, - Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[33]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[34]}, }, { Name: "billinginvoiceline_namespace_parent_line_id", Unique: false, - Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[36]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[37]}, }, { Name: "billinginvoiceline_namespace_parent_line_id_child_unique_reference_id", Unique: true, - Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[36], BillingInvoiceLinesColumns[28]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[37], BillingInvoiceLinesColumns[28]}, Annotation: &entsql.IndexAnnotation{ Where: "child_unique_reference_id IS NOT NULL AND deleted_at IS NULL", }, @@ -900,7 +901,7 @@ var ( { Name: "billinginvoiceline_namespace_subscription_id_subscription_phase_id_subscription_item_id", Unique: false, - Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[39], BillingInvoiceLinesColumns[41], BillingInvoiceLinesColumns[40]}, + Columns: []*schema.Column{BillingInvoiceLinesColumns[2], BillingInvoiceLinesColumns[40], BillingInvoiceLinesColumns[42], BillingInvoiceLinesColumns[41]}, }, }, } @@ -1920,6 +1921,255 @@ var ( }, }, } + // ChargeUsageBasedColumns holds the columns for the "charge_usage_based" table. + ChargeUsageBasedColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "invoice_at", Type: field.TypeTime}, + {Name: "settlement_mode", Type: field.TypeEnum, Enums: []string{"invoice_only", "credit_then_invoice", "credit_only"}}, + {Name: "discounts", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "feature_key", Type: field.TypeString}, + {Name: "price", Type: field.TypeString, SchemaType: map[string]string{"postgres": "jsonb"}}, + } + // ChargeUsageBasedTable holds the schema information for the "charge_usage_based" table. + ChargeUsageBasedTable = &schema.Table{ + Name: "charge_usage_based", + Columns: ChargeUsageBasedColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_charges_usage_based", + Columns: []*schema.Column{ChargeUsageBasedColumns[0]}, + RefColumns: []*schema.Column{ChargesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebased_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedColumns[1]}, + }, + { + Name: "chargeusagebased_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedColumns[0]}, + }, + { + Name: "chargeusagebased_namespace_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedColumns[1], ChargeUsageBasedColumns[0]}, + }, + }, + } + // ChargeUsageBasedRunCreditAllocationsColumns holds the columns for the "charge_usage_based_run_credit_allocations" table. + ChargeUsageBasedRunCreditAllocationsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "line_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "ledger_transaction_group_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "run_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeUsageBasedRunCreditAllocationsTable holds the schema information for the "charge_usage_based_run_credit_allocations" table. + ChargeUsageBasedRunCreditAllocationsTable = &schema.Table{ + Name: "charge_usage_based_run_credit_allocations", + Columns: ChargeUsageBasedRunCreditAllocationsColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_run_credit_allocations_charge_usage_based_runs_credit_allocations", + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[11]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedruncreditallocations_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[6]}, + }, + { + Name: "chargeusagebasedruncreditallocations_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[0]}, + }, + { + Name: "chargeusagebasedruncreditallocations_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunCreditAllocationsColumns[10]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // ChargeUsageBasedRunInvoicedUsagesColumns holds the columns for the "charge_usage_based_run_invoiced_usages" table. + ChargeUsageBasedRunInvoicedUsagesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "line_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "mutable", Type: field.TypeBool}, + {Name: "ledger_transaction_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "taxes_total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "taxes_inclusive_total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "taxes_exclusive_total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "charges_total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "discounts_total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "credits_total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "total", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "run_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeUsageBasedRunInvoicedUsagesTable holds the schema information for the "charge_usage_based_run_invoiced_usages" table. + ChargeUsageBasedRunInvoicedUsagesTable = &schema.Table{ + Name: "charge_usage_based_run_invoiced_usages", + Columns: ChargeUsageBasedRunInvoicedUsagesColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_run_invoiced_usages_charge_usage_based_runs_invoiced_usage", + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[19]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedruninvoicedusage_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[6]}, + }, + { + Name: "chargeusagebasedruninvoicedusage_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[0]}, + }, + { + Name: "chargeusagebasedruninvoicedusage_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunInvoicedUsagesColumns[10]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // ChargeUsageBasedRunPaymentsColumns holds the columns for the "charge_usage_based_run_payments" table. + ChargeUsageBasedRunPaymentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "line_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "service_period_from", Type: field.TypeTime}, + {Name: "service_period_to", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"authorized", "settled"}}, + {Name: "amount", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "authorized_transaction_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "authorized_at", Type: field.TypeTime, Nullable: true}, + {Name: "settled_transaction_group_id", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "settled_at", Type: field.TypeTime, Nullable: true}, + {Name: "namespace", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "annotations", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "run_id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeUsageBasedRunPaymentsTable holds the schema information for the "charge_usage_based_run_payments" table. + ChargeUsageBasedRunPaymentsTable = &schema.Table{ + Name: "charge_usage_based_run_payments", + Columns: ChargeUsageBasedRunPaymentsColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_run_payments_charge_usage_based_runs_payment", + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[15]}, + RefColumns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedrunpayment_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[10]}, + }, + { + Name: "chargeusagebasedrunpayment_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[0]}, + }, + { + Name: "chargeusagebasedrunpayment_annotations", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunPaymentsColumns[14]}, + Annotation: &entsql.IndexAnnotation{ + Types: map[string]string{ + "postgres": "GIN", + }, + }, + }, + }, + } + // ChargeUsageBasedRunsColumns holds the columns for the "charge_usage_based_runs" table. + ChargeUsageBasedRunsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, + {Name: "namespace", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"invoice"}}, + {Name: "asof", Type: field.TypeTime}, + {Name: "meter_value", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "numeric"}}, + {Name: "charge_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "char(26)"}}, + } + // ChargeUsageBasedRunsTable holds the schema information for the "charge_usage_based_runs" table. + ChargeUsageBasedRunsTable = &schema.Table{ + Name: "charge_usage_based_runs", + Columns: ChargeUsageBasedRunsColumns, + PrimaryKey: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "charge_usage_based_runs_charge_usage_based_runs", + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[8]}, + RefColumns: []*schema.Column{ChargeUsageBasedColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "chargeusagebasedruns_namespace", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[1]}, + }, + { + Name: "chargeusagebasedruns_id", + Unique: true, + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[0]}, + }, + { + Name: "chargeusagebasedruns_namespace_charge_id", + Unique: false, + Columns: []*schema.Column{ChargeUsageBasedRunsColumns[1], ChargeUsageBasedRunsColumns[8]}, + }, + }, + } // CurrencyCostBasesColumns holds the columns for the "currency_cost_bases" table. CurrencyCostBasesColumns = []*schema.Column{ {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "char(26)"}}, @@ -3569,6 +3819,11 @@ var ( ChargeFlatFeeCreditAllocationsTable, ChargeFlatFeeInvoicedUsagesTable, ChargeFlatFeePaymentsTable, + ChargeUsageBasedTable, + ChargeUsageBasedRunCreditAllocationsTable, + ChargeUsageBasedRunInvoicedUsagesTable, + ChargeUsageBasedRunPaymentsTable, + ChargeUsageBasedRunsTable, CurrencyCostBasesTable, CustomCurrenciesTable, CustomersTable, @@ -3656,6 +3911,14 @@ func init() { ChargeFlatFeeInvoicedUsagesTable.ForeignKeys[1].RefTable = ChargeFlatFeesTable ChargeFlatFeePaymentsTable.ForeignKeys[0].RefTable = BillingInvoiceLinesTable ChargeFlatFeePaymentsTable.ForeignKeys[1].RefTable = ChargeFlatFeesTable + ChargeUsageBasedTable.ForeignKeys[0].RefTable = ChargesTable + ChargeUsageBasedTable.Annotation = &entsql.Annotation{ + Table: "charge_usage_based", + } + ChargeUsageBasedRunCreditAllocationsTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunInvoicedUsagesTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunPaymentsTable.ForeignKeys[0].RefTable = ChargeUsageBasedRunsTable + ChargeUsageBasedRunsTable.ForeignKeys[0].RefTable = ChargeUsageBasedTable CurrencyCostBasesTable.ForeignKeys[0].RefTable = CustomCurrenciesTable CustomerSubjectsTable.ForeignKeys[0].RefTable = CustomersTable EntitlementsTable.ForeignKeys[0].RefTable = CustomersTable diff --git a/openmeter/ent/db/mutation.go b/openmeter/ent/db/mutation.go index 66fcb15430..acce67174f 100644 --- a/openmeter/ent/db/mutation.go +++ b/openmeter/ent/db/mutation.go @@ -18,6 +18,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/billing/charges/flatfee" "github.com/openmeterio/openmeter/openmeter/billing/charges/meta" "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" "github.com/openmeterio/openmeter/openmeter/credit/balance" "github.com/openmeterio/openmeter/openmeter/credit/grant" "github.com/openmeterio/openmeter/openmeter/ent/db/addon" @@ -52,6 +53,11 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeecreditallocations" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeinvoicedusage" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeepayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" @@ -131,6 +137,11 @@ const ( TypeChargeFlatFeeCreditAllocations = "ChargeFlatFeeCreditAllocations" TypeChargeFlatFeeInvoicedUsage = "ChargeFlatFeeInvoicedUsage" TypeChargeFlatFeePayment = "ChargeFlatFeePayment" + TypeChargeUsageBased = "ChargeUsageBased" + TypeChargeUsageBasedRunCreditAllocations = "ChargeUsageBasedRunCreditAllocations" + TypeChargeUsageBasedRunInvoicedUsage = "ChargeUsageBasedRunInvoicedUsage" + TypeChargeUsageBasedRunPayment = "ChargeUsageBasedRunPayment" + TypeChargeUsageBasedRuns = "ChargeUsageBasedRuns" TypeCurrencyCostBasis = "CurrencyCostBasis" TypeCustomCurrency = "CustomCurrency" TypeCustomer = "Customer" @@ -16744,6 +16755,7 @@ type BillingInvoiceLineMutation struct { child_unique_reference_id *string subscription_billing_period_from *time.Time subscription_billing_period_to *time.Time + lifecycle_handler *billing.LifecycleHandler line_ids *string credits_applied **billing.CreditsApplied clearedFields map[string]struct{} @@ -18447,6 +18459,42 @@ func (m *BillingInvoiceLineMutation) ResetChargeID() { delete(m.clearedFields, billinginvoiceline.FieldChargeID) } +// SetLifecycleHandler sets the "lifecycle_handler" field. +func (m *BillingInvoiceLineMutation) SetLifecycleHandler(bh billing.LifecycleHandler) { + m.lifecycle_handler = &bh +} + +// LifecycleHandler returns the value of the "lifecycle_handler" field in the mutation. +func (m *BillingInvoiceLineMutation) LifecycleHandler() (r billing.LifecycleHandler, exists bool) { + v := m.lifecycle_handler + if v == nil { + return + } + return *v, true +} + +// OldLifecycleHandler returns the old "lifecycle_handler" field's value of the BillingInvoiceLine entity. +// If the BillingInvoiceLine object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BillingInvoiceLineMutation) OldLifecycleHandler(ctx context.Context) (v billing.LifecycleHandler, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLifecycleHandler is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLifecycleHandler requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLifecycleHandler: %w", err) + } + return oldValue.LifecycleHandler, nil +} + +// ResetLifecycleHandler resets all changes to the "lifecycle_handler" field. +func (m *BillingInvoiceLineMutation) ResetLifecycleHandler() { + m.lifecycle_handler = nil +} + // SetLineIds sets the "line_ids" field. func (m *BillingInvoiceLineMutation) SetLineIds(s string) { m.line_ids = &s @@ -19222,7 +19270,7 @@ func (m *BillingInvoiceLineMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *BillingInvoiceLineMutation) Fields() []string { - fields := make([]string, 0, 39) + fields := make([]string, 0, 40) if m.annotations != nil { fields = append(fields, billinginvoiceline.FieldAnnotations) } @@ -19334,6 +19382,9 @@ func (m *BillingInvoiceLineMutation) Fields() []string { if m.charge != nil { fields = append(fields, billinginvoiceline.FieldChargeID) } + if m.lifecycle_handler != nil { + fields = append(fields, billinginvoiceline.FieldLifecycleHandler) + } if m.line_ids != nil { fields = append(fields, billinginvoiceline.FieldLineIds) } @@ -19422,6 +19473,8 @@ func (m *BillingInvoiceLineMutation) Field(name string) (ent.Value, bool) { return m.SplitLineGroupID() case billinginvoiceline.FieldChargeID: return m.ChargeID() + case billinginvoiceline.FieldLifecycleHandler: + return m.LifecycleHandler() case billinginvoiceline.FieldLineIds: return m.LineIds() case billinginvoiceline.FieldCreditsApplied: @@ -19509,6 +19562,8 @@ func (m *BillingInvoiceLineMutation) OldField(ctx context.Context, name string) return m.OldSplitLineGroupID(ctx) case billinginvoiceline.FieldChargeID: return m.OldChargeID(ctx) + case billinginvoiceline.FieldLifecycleHandler: + return m.OldLifecycleHandler(ctx) case billinginvoiceline.FieldLineIds: return m.OldLineIds(ctx) case billinginvoiceline.FieldCreditsApplied: @@ -19781,6 +19836,13 @@ func (m *BillingInvoiceLineMutation) SetField(name string, value ent.Value) erro } m.SetChargeID(v) return nil + case billinginvoiceline.FieldLifecycleHandler: + v, ok := value.(billing.LifecycleHandler) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLifecycleHandler(v) + return nil case billinginvoiceline.FieldLineIds: v, ok := value.(string) if !ok { @@ -20072,6 +20134,9 @@ func (m *BillingInvoiceLineMutation) ResetField(name string) error { case billinginvoiceline.FieldChargeID: m.ResetChargeID() return nil + case billinginvoiceline.FieldLifecycleHandler: + m.ResetLifecycleHandler() + return nil case billinginvoiceline.FieldLineIds: m.ResetLineIds() return nil @@ -34108,6 +34173,8 @@ type ChargeMutation struct { clearedflat_fee bool credit_purchase *string clearedcredit_purchase bool + usage_based *string + clearedusage_based bool billing_invoice_lines map[string]struct{} removedbilling_invoice_lines map[string]struct{} clearedbilling_invoice_lines bool @@ -35241,6 +35308,45 @@ func (m *ChargeMutation) ResetCreditPurchase() { m.clearedcredit_purchase = false } +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by id. +func (m *ChargeMutation) SetUsageBasedID(id string) { + m.usage_based = &id +} + +// ClearUsageBased clears the "usage_based" edge to the ChargeUsageBased entity. +func (m *ChargeMutation) ClearUsageBased() { + m.clearedusage_based = true +} + +// UsageBasedCleared reports if the "usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *ChargeMutation) UsageBasedCleared() bool { + return m.clearedusage_based +} + +// UsageBasedID returns the "usage_based" edge ID in the mutation. +func (m *ChargeMutation) UsageBasedID() (id string, exists bool) { + if m.usage_based != nil { + return *m.usage_based, true + } + return +} + +// UsageBasedIDs returns the "usage_based" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UsageBasedID instead. It exists only for internal usage by the builders. +func (m *ChargeMutation) UsageBasedIDs() (ids []string) { + if id := m.usage_based; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUsageBased resets all changes to the "usage_based" edge. +func (m *ChargeMutation) ResetUsageBased() { + m.usage_based = nil + m.clearedusage_based = false +} + // AddBillingInvoiceLineIDs adds the "billing_invoice_lines" edge to the BillingInvoiceLine entity by ids. func (m *ChargeMutation) AddBillingInvoiceLineIDs(ids ...string) { if m.billing_invoice_lines == nil { @@ -36015,13 +36121,16 @@ func (m *ChargeMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *ChargeMutation) AddedEdges() []string { - edges := make([]string, 0, 8) + edges := make([]string, 0, 9) if m.flat_fee != nil { edges = append(edges, charge.EdgeFlatFee) } if m.credit_purchase != nil { edges = append(edges, charge.EdgeCreditPurchase) } + if m.usage_based != nil { + edges = append(edges, charge.EdgeUsageBased) + } if m.billing_invoice_lines != nil { edges = append(edges, charge.EdgeBillingInvoiceLines) } @@ -36055,6 +36164,10 @@ func (m *ChargeMutation) AddedIDs(name string) []ent.Value { if id := m.credit_purchase; id != nil { return []ent.Value{*id} } + case charge.EdgeUsageBased: + if id := m.usage_based; id != nil { + return []ent.Value{*id} + } case charge.EdgeBillingInvoiceLines: ids := make([]ent.Value, 0, len(m.billing_invoice_lines)) for id := range m.billing_invoice_lines { @@ -36089,7 +36202,7 @@ func (m *ChargeMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *ChargeMutation) RemovedEdges() []string { - edges := make([]string, 0, 8) + edges := make([]string, 0, 9) if m.removedbilling_invoice_lines != nil { edges = append(edges, charge.EdgeBillingInvoiceLines) } @@ -36121,13 +36234,16 @@ func (m *ChargeMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *ChargeMutation) ClearedEdges() []string { - edges := make([]string, 0, 8) + edges := make([]string, 0, 9) if m.clearedflat_fee { edges = append(edges, charge.EdgeFlatFee) } if m.clearedcredit_purchase { edges = append(edges, charge.EdgeCreditPurchase) } + if m.clearedusage_based { + edges = append(edges, charge.EdgeUsageBased) + } if m.clearedbilling_invoice_lines { edges = append(edges, charge.EdgeBillingInvoiceLines) } @@ -36157,6 +36273,8 @@ func (m *ChargeMutation) EdgeCleared(name string) bool { return m.clearedflat_fee case charge.EdgeCreditPurchase: return m.clearedcredit_purchase + case charge.EdgeUsageBased: + return m.clearedusage_based case charge.EdgeBillingInvoiceLines: return m.clearedbilling_invoice_lines case charge.EdgeBillingSplitLineGroups: @@ -36183,6 +36301,9 @@ func (m *ChargeMutation) ClearEdge(name string) error { case charge.EdgeCreditPurchase: m.ClearCreditPurchase() return nil + case charge.EdgeUsageBased: + m.ClearUsageBased() + return nil case charge.EdgeCustomer: m.ClearCustomer() return nil @@ -36209,6 +36330,9 @@ func (m *ChargeMutation) ResetEdge(name string) error { case charge.EdgeCreditPurchase: m.ResetCreditPurchase() return nil + case charge.EdgeUsageBased: + m.ResetUsageBased() + return nil case charge.EdgeBillingInvoiceLines: m.ResetBillingInvoiceLines() return nil @@ -43137,6 +43261,5466 @@ func (m *ChargeFlatFeePaymentMutation) ResetEdge(name string) error { return fmt.Errorf("unknown ChargeFlatFeePayment edge %s", name) } +// ChargeUsageBasedMutation represents an operation that mutates the ChargeUsageBased nodes in the graph. +type ChargeUsageBasedMutation struct { + config + op Op + typ string + id *string + namespace *string + invoice_at *time.Time + settlement_mode *productcatalog.SettlementMode + discounts **productcatalog.Discounts + feature_key *string + price **productcatalog.Price + clearedFields map[string]struct{} + charge *string + clearedcharge bool + runs map[string]struct{} + removedruns map[string]struct{} + clearedruns bool + done bool + oldValue func(context.Context) (*ChargeUsageBased, error) + predicates []predicate.ChargeUsageBased +} + +var _ ent.Mutation = (*ChargeUsageBasedMutation)(nil) + +// chargeusagebasedOption allows management of the mutation configuration using functional options. +type chargeusagebasedOption func(*ChargeUsageBasedMutation) + +// newChargeUsageBasedMutation creates new mutation for the ChargeUsageBased entity. +func newChargeUsageBasedMutation(c config, op Op, opts ...chargeusagebasedOption) *ChargeUsageBasedMutation { + m := &ChargeUsageBasedMutation{ + config: c, + op: op, + typ: TypeChargeUsageBased, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedID sets the ID field of the mutation. +func withChargeUsageBasedID(id string) chargeusagebasedOption { + return func(m *ChargeUsageBasedMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBased + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBased, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBased.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBased sets the old ChargeUsageBased of the mutation. +func withChargeUsageBased(node *ChargeUsageBased) chargeusagebasedOption { + return func(m *ChargeUsageBasedMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBased, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ChargeUsageBasedMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ChargeUsageBasedMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ChargeUsageBased entities. +func (m *ChargeUsageBasedMutation) SetID(id string) { + m.id = &id +} + +// 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 *ChargeUsageBasedMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + 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 *ChargeUsageBasedMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ChargeUsageBased.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeUsageBasedMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the ChargeUsageBased entity. +// If the ChargeUsageBased object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *ChargeUsageBasedMutation) ResetNamespace() { + m.namespace = nil +} + +// SetInvoiceAt sets the "invoice_at" field. +func (m *ChargeUsageBasedMutation) SetInvoiceAt(t time.Time) { + m.invoice_at = &t +} + +// InvoiceAt returns the value of the "invoice_at" field in the mutation. +func (m *ChargeUsageBasedMutation) InvoiceAt() (r time.Time, exists bool) { + v := m.invoice_at + if v == nil { + return + } + return *v, true +} + +// OldInvoiceAt returns the old "invoice_at" field's value of the ChargeUsageBased entity. +// If the ChargeUsageBased object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedMutation) OldInvoiceAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInvoiceAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInvoiceAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInvoiceAt: %w", err) + } + return oldValue.InvoiceAt, nil +} + +// ResetInvoiceAt resets all changes to the "invoice_at" field. +func (m *ChargeUsageBasedMutation) ResetInvoiceAt() { + m.invoice_at = nil +} + +// SetSettlementMode sets the "settlement_mode" field. +func (m *ChargeUsageBasedMutation) SetSettlementMode(pm productcatalog.SettlementMode) { + m.settlement_mode = &pm +} + +// SettlementMode returns the value of the "settlement_mode" field in the mutation. +func (m *ChargeUsageBasedMutation) SettlementMode() (r productcatalog.SettlementMode, exists bool) { + v := m.settlement_mode + if v == nil { + return + } + return *v, true +} + +// OldSettlementMode returns the old "settlement_mode" field's value of the ChargeUsageBased entity. +// If the ChargeUsageBased object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedMutation) OldSettlementMode(ctx context.Context) (v productcatalog.SettlementMode, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSettlementMode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSettlementMode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSettlementMode: %w", err) + } + return oldValue.SettlementMode, nil +} + +// ResetSettlementMode resets all changes to the "settlement_mode" field. +func (m *ChargeUsageBasedMutation) ResetSettlementMode() { + m.settlement_mode = nil +} + +// SetDiscounts sets the "discounts" field. +func (m *ChargeUsageBasedMutation) SetDiscounts(pr *productcatalog.Discounts) { + m.discounts = &pr +} + +// Discounts returns the value of the "discounts" field in the mutation. +func (m *ChargeUsageBasedMutation) Discounts() (r *productcatalog.Discounts, exists bool) { + v := m.discounts + if v == nil { + return + } + return *v, true +} + +// OldDiscounts returns the old "discounts" field's value of the ChargeUsageBased entity. +// If the ChargeUsageBased object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedMutation) OldDiscounts(ctx context.Context) (v *productcatalog.Discounts, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDiscounts is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDiscounts requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDiscounts: %w", err) + } + return oldValue.Discounts, nil +} + +// ClearDiscounts clears the value of the "discounts" field. +func (m *ChargeUsageBasedMutation) ClearDiscounts() { + m.discounts = nil + m.clearedFields[chargeusagebased.FieldDiscounts] = struct{}{} +} + +// DiscountsCleared returns if the "discounts" field was cleared in this mutation. +func (m *ChargeUsageBasedMutation) DiscountsCleared() bool { + _, ok := m.clearedFields[chargeusagebased.FieldDiscounts] + return ok +} + +// ResetDiscounts resets all changes to the "discounts" field. +func (m *ChargeUsageBasedMutation) ResetDiscounts() { + m.discounts = nil + delete(m.clearedFields, chargeusagebased.FieldDiscounts) +} + +// SetFeatureKey sets the "feature_key" field. +func (m *ChargeUsageBasedMutation) SetFeatureKey(s string) { + m.feature_key = &s +} + +// FeatureKey returns the value of the "feature_key" field in the mutation. +func (m *ChargeUsageBasedMutation) FeatureKey() (r string, exists bool) { + v := m.feature_key + if v == nil { + return + } + return *v, true +} + +// OldFeatureKey returns the old "feature_key" field's value of the ChargeUsageBased entity. +// If the ChargeUsageBased object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedMutation) OldFeatureKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFeatureKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFeatureKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFeatureKey: %w", err) + } + return oldValue.FeatureKey, nil +} + +// ResetFeatureKey resets all changes to the "feature_key" field. +func (m *ChargeUsageBasedMutation) ResetFeatureKey() { + m.feature_key = nil +} + +// SetPrice sets the "price" field. +func (m *ChargeUsageBasedMutation) SetPrice(pr *productcatalog.Price) { + m.price = &pr +} + +// Price returns the value of the "price" field in the mutation. +func (m *ChargeUsageBasedMutation) Price() (r *productcatalog.Price, exists bool) { + v := m.price + if v == nil { + return + } + return *v, true +} + +// OldPrice returns the old "price" field's value of the ChargeUsageBased entity. +// If the ChargeUsageBased object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedMutation) OldPrice(ctx context.Context) (v *productcatalog.Price, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPrice is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPrice requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPrice: %w", err) + } + return oldValue.Price, nil +} + +// ResetPrice resets all changes to the "price" field. +func (m *ChargeUsageBasedMutation) ResetPrice() { + m.price = nil +} + +// SetChargeID sets the "charge" edge to the Charge entity by id. +func (m *ChargeUsageBasedMutation) SetChargeID(id string) { + m.charge = &id +} + +// ClearCharge clears the "charge" edge to the Charge entity. +func (m *ChargeUsageBasedMutation) ClearCharge() { + m.clearedcharge = true +} + +// ChargeCleared reports if the "charge" edge to the Charge entity was cleared. +func (m *ChargeUsageBasedMutation) ChargeCleared() bool { + return m.clearedcharge +} + +// ChargeID returns the "charge" edge ID in the mutation. +func (m *ChargeUsageBasedMutation) ChargeID() (id string, exists bool) { + if m.charge != nil { + return *m.charge, true + } + return +} + +// ChargeIDs returns the "charge" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ChargeID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedMutation) ChargeIDs() (ids []string) { + if id := m.charge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCharge resets all changes to the "charge" edge. +func (m *ChargeUsageBasedMutation) ResetCharge() { + m.charge = nil + m.clearedcharge = false +} + +// AddRunIDs adds the "runs" edge to the ChargeUsageBasedRuns entity by ids. +func (m *ChargeUsageBasedMutation) AddRunIDs(ids ...string) { + if m.runs == nil { + m.runs = make(map[string]struct{}) + } + for i := range ids { + m.runs[ids[i]] = struct{}{} + } +} + +// ClearRuns clears the "runs" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedMutation) ClearRuns() { + m.clearedruns = true +} + +// RunsCleared reports if the "runs" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedMutation) RunsCleared() bool { + return m.clearedruns +} + +// RemoveRunIDs removes the "runs" edge to the ChargeUsageBasedRuns entity by IDs. +func (m *ChargeUsageBasedMutation) RemoveRunIDs(ids ...string) { + if m.removedruns == nil { + m.removedruns = make(map[string]struct{}) + } + for i := range ids { + delete(m.runs, ids[i]) + m.removedruns[ids[i]] = struct{}{} + } +} + +// RemovedRuns returns the removed IDs of the "runs" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedMutation) RemovedRunsIDs() (ids []string) { + for id := range m.removedruns { + ids = append(ids, id) + } + return +} + +// RunsIDs returns the "runs" edge IDs in the mutation. +func (m *ChargeUsageBasedMutation) RunsIDs() (ids []string) { + for id := range m.runs { + ids = append(ids, id) + } + return +} + +// ResetRuns resets all changes to the "runs" edge. +func (m *ChargeUsageBasedMutation) ResetRuns() { + m.runs = nil + m.clearedruns = false + m.removedruns = nil +} + +// Where appends a list predicates to the ChargeUsageBasedMutation builder. +func (m *ChargeUsageBasedMutation) Where(ps ...predicate.ChargeUsageBased) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBased, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBased). +func (m *ChargeUsageBasedMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ChargeUsageBasedMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.namespace != nil { + fields = append(fields, chargeusagebased.FieldNamespace) + } + if m.invoice_at != nil { + fields = append(fields, chargeusagebased.FieldInvoiceAt) + } + if m.settlement_mode != nil { + fields = append(fields, chargeusagebased.FieldSettlementMode) + } + if m.discounts != nil { + fields = append(fields, chargeusagebased.FieldDiscounts) + } + if m.feature_key != nil { + fields = append(fields, chargeusagebased.FieldFeatureKey) + } + if m.price != nil { + fields = append(fields, chargeusagebased.FieldPrice) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ChargeUsageBasedMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebased.FieldNamespace: + return m.Namespace() + case chargeusagebased.FieldInvoiceAt: + return m.InvoiceAt() + case chargeusagebased.FieldSettlementMode: + return m.SettlementMode() + case chargeusagebased.FieldDiscounts: + return m.Discounts() + case chargeusagebased.FieldFeatureKey: + return m.FeatureKey() + case chargeusagebased.FieldPrice: + return m.Price() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ChargeUsageBasedMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebased.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebased.FieldInvoiceAt: + return m.OldInvoiceAt(ctx) + case chargeusagebased.FieldSettlementMode: + return m.OldSettlementMode(ctx) + case chargeusagebased.FieldDiscounts: + return m.OldDiscounts(ctx) + case chargeusagebased.FieldFeatureKey: + return m.OldFeatureKey(ctx) + case chargeusagebased.FieldPrice: + return m.OldPrice(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBased field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebased.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebased.FieldInvoiceAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInvoiceAt(v) + return nil + case chargeusagebased.FieldSettlementMode: + v, ok := value.(productcatalog.SettlementMode) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettlementMode(v) + return nil + case chargeusagebased.FieldDiscounts: + v, ok := value.(*productcatalog.Discounts) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDiscounts(v) + return nil + case chargeusagebased.FieldFeatureKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFeatureKey(v) + return nil + case chargeusagebased.FieldPrice: + v, ok := value.(*productcatalog.Price) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrice(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBased field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ChargeUsageBasedMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeUsageBased numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebased.FieldDiscounts) { + fields = append(fields, chargeusagebased.FieldDiscounts) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ChargeUsageBasedMutation) ClearField(name string) error { + switch name { + case chargeusagebased.FieldDiscounts: + m.ClearDiscounts() + return nil + } + return fmt.Errorf("unknown ChargeUsageBased nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ChargeUsageBasedMutation) ResetField(name string) error { + switch name { + case chargeusagebased.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebased.FieldInvoiceAt: + m.ResetInvoiceAt() + return nil + case chargeusagebased.FieldSettlementMode: + m.ResetSettlementMode() + return nil + case chargeusagebased.FieldDiscounts: + m.ResetDiscounts() + return nil + case chargeusagebased.FieldFeatureKey: + m.ResetFeatureKey() + return nil + case chargeusagebased.FieldPrice: + m.ResetPrice() + return nil + } + return fmt.Errorf("unknown ChargeUsageBased field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.charge != nil { + edges = append(edges, chargeusagebased.EdgeCharge) + } + if m.runs != nil { + edges = append(edges, chargeusagebased.EdgeRuns) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebased.EdgeCharge: + if id := m.charge; id != nil { + return []ent.Value{*id} + } + case chargeusagebased.EdgeRuns: + ids := make([]ent.Value, 0, len(m.runs)) + for id := range m.runs { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedruns != nil { + edges = append(edges, chargeusagebased.EdgeRuns) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedMutation) RemovedIDs(name string) []ent.Value { + switch name { + case chargeusagebased.EdgeRuns: + ids := make([]ent.Value, 0, len(m.removedruns)) + for id := range m.removedruns { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedcharge { + edges = append(edges, chargeusagebased.EdgeCharge) + } + if m.clearedruns { + edges = append(edges, chargeusagebased.EdgeRuns) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebased.EdgeCharge: + return m.clearedcharge + case chargeusagebased.EdgeRuns: + return m.clearedruns + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ChargeUsageBasedMutation) ClearEdge(name string) error { + switch name { + case chargeusagebased.EdgeCharge: + m.ClearCharge() + return nil + } + return fmt.Errorf("unknown ChargeUsageBased unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ChargeUsageBasedMutation) ResetEdge(name string) error { + switch name { + case chargeusagebased.EdgeCharge: + m.ResetCharge() + return nil + case chargeusagebased.EdgeRuns: + m.ResetRuns() + return nil + } + return fmt.Errorf("unknown ChargeUsageBased edge %s", name) +} + +// ChargeUsageBasedRunCreditAllocationsMutation represents an operation that mutates the ChargeUsageBasedRunCreditAllocations nodes in the graph. +type ChargeUsageBasedRunCreditAllocationsMutation struct { + config + op Op + typ string + id *string + line_id *string + amount *alpacadecimal.Decimal + service_period_from *time.Time + service_period_to *time.Time + ledger_transaction_group_id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + clearedFields map[string]struct{} + run *string + clearedrun bool + done bool + oldValue func(context.Context) (*ChargeUsageBasedRunCreditAllocations, error) + predicates []predicate.ChargeUsageBasedRunCreditAllocations +} + +var _ ent.Mutation = (*ChargeUsageBasedRunCreditAllocationsMutation)(nil) + +// chargeusagebasedruncreditallocationsOption allows management of the mutation configuration using functional options. +type chargeusagebasedruncreditallocationsOption func(*ChargeUsageBasedRunCreditAllocationsMutation) + +// newChargeUsageBasedRunCreditAllocationsMutation creates new mutation for the ChargeUsageBasedRunCreditAllocations entity. +func newChargeUsageBasedRunCreditAllocationsMutation(c config, op Op, opts ...chargeusagebasedruncreditallocationsOption) *ChargeUsageBasedRunCreditAllocationsMutation { + m := &ChargeUsageBasedRunCreditAllocationsMutation{ + config: c, + op: op, + typ: TypeChargeUsageBasedRunCreditAllocations, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedRunCreditAllocationsID sets the ID field of the mutation. +func withChargeUsageBasedRunCreditAllocationsID(id string) chargeusagebasedruncreditallocationsOption { + return func(m *ChargeUsageBasedRunCreditAllocationsMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBasedRunCreditAllocations + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBasedRunCreditAllocations.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBasedRunCreditAllocations sets the old ChargeUsageBasedRunCreditAllocations of the mutation. +func withChargeUsageBasedRunCreditAllocations(node *ChargeUsageBasedRunCreditAllocations) chargeusagebasedruncreditallocationsOption { + return func(m *ChargeUsageBasedRunCreditAllocationsMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBasedRunCreditAllocations, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ChargeUsageBasedRunCreditAllocationsMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ChargeUsageBasedRunCreditAllocationsMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ChargeUsageBasedRunCreditAllocations entities. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetID(id string) { + m.id = &id +} + +// 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 *ChargeUsageBasedRunCreditAllocationsMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + 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 *ChargeUsageBasedRunCreditAllocationsMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ChargeUsageBasedRunCreditAllocations.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetLineID sets the "line_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetLineID(s string) { + m.line_id = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) LineID() (r string, exists bool) { + v := m.line_id + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldLineID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLineID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLineID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLineID: %w", err) + } + return oldValue.LineID, nil +} + +// ClearLineID clears the value of the "line_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearLineID() { + m.line_id = nil + m.clearedFields[chargeusagebasedruncreditallocations.FieldLineID] = struct{}{} +} + +// LineIDCleared returns if the "line_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) LineIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruncreditallocations.FieldLineID] + return ok +} + +// ResetLineID resets all changes to the "line_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetLineID() { + m.line_id = nil + delete(m.clearedFields, chargeusagebasedruncreditallocations.FieldLineID) +} + +// SetAmount sets the "amount" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Amount() (r alpacadecimal.Decimal, exists bool) { + v := m.amount + if v == nil { + return + } + return *v, true +} + +// OldAmount returns the old "amount" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmount: %w", err) + } + return oldValue.Amount, nil +} + +// ResetAmount resets all changes to the "amount" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetAmount() { + m.amount = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ServicePeriodFrom() (r time.Time, exists bool) { + v := m.service_period_from + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodFrom returns the old "service_period_from" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodFrom: %w", err) + } + return oldValue.ServicePeriodFrom, nil +} + +// ResetServicePeriodFrom resets all changes to the "service_period_from" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ServicePeriodTo() (r time.Time, exists bool) { + v := m.service_period_to + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodTo returns the old "service_period_to" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodTo: %w", err) + } + return oldValue.ServicePeriodTo, nil +} + +// ResetServicePeriodTo resets all changes to the "service_period_to" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetLedgerTransactionGroupID(s string) { + m.ledger_transaction_group_id = &s +} + +// LedgerTransactionGroupID returns the value of the "ledger_transaction_group_id" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) LedgerTransactionGroupID() (r string, exists bool) { + v := m.ledger_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldLedgerTransactionGroupID returns the old "ledger_transaction_group_id" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldLedgerTransactionGroupID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLedgerTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLedgerTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLedgerTransactionGroupID: %w", err) + } + return oldValue.LedgerTransactionGroupID, nil +} + +// ResetLedgerTransactionGroupID resets all changes to the "ledger_transaction_group_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetLedgerTransactionGroupID() { + m.ledger_transaction_group_id = nil +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeusagebasedruncreditallocations.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruncreditallocations.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeusagebasedruncreditallocations.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Annotations() (r models.Annotations, exists bool) { + v := m.annotations + if v == nil { + return + } + return *v, true +} + +// OldAnnotations returns the old "annotations" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldAnnotations(ctx context.Context) (v models.Annotations, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAnnotations is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAnnotations requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAnnotations: %w", err) + } + return oldValue.Annotations, nil +} + +// ClearAnnotations clears the value of the "annotations" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeusagebasedruncreditallocations.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruncreditallocations.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeusagebasedruncreditallocations.FieldAnnotations) +} + +// SetRunID sets the "run_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RunID() (r string, exists bool) { + v := m.run + if v == nil { + return + } + return *v, true +} + +// OldRunID returns the old "run_id" field's value of the ChargeUsageBasedRunCreditAllocations entity. +// If the ChargeUsageBasedRunCreditAllocations object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldRunID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRunID: %w", err) + } + return oldValue.RunID, nil +} + +// ResetRunID resets all changes to the "run_id" field. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetRunID() { + m.run = nil +} + +// ClearRun clears the "run" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeusagebasedruncreditallocations.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RunCleared() bool { + return m.clearedrun +} + +// RunIDs returns the "run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RunID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// Where appends a list predicates to the ChargeUsageBasedRunCreditAllocationsMutation builder. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Where(ps ...predicate.ChargeUsageBasedRunCreditAllocations) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedRunCreditAllocationsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBasedRunCreditAllocations, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBasedRunCreditAllocations). +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.line_id != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldLineID) + } + if m.amount != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldAmount) + } + if m.service_period_from != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldServicePeriodTo) + } + if m.ledger_transaction_group_id != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID) + } + if m.namespace != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldAnnotations) + } + if m.run != nil { + fields = append(fields, chargeusagebasedruncreditallocations.FieldRunID) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedruncreditallocations.FieldLineID: + return m.LineID() + case chargeusagebasedruncreditallocations.FieldAmount: + return m.Amount() + case chargeusagebasedruncreditallocations.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeusagebasedruncreditallocations.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID: + return m.LedgerTransactionGroupID() + case chargeusagebasedruncreditallocations.FieldNamespace: + return m.Namespace() + case chargeusagebasedruncreditallocations.FieldCreatedAt: + return m.CreatedAt() + case chargeusagebasedruncreditallocations.FieldUpdatedAt: + return m.UpdatedAt() + case chargeusagebasedruncreditallocations.FieldDeletedAt: + return m.DeletedAt() + case chargeusagebasedruncreditallocations.FieldAnnotations: + return m.Annotations() + case chargeusagebasedruncreditallocations.FieldRunID: + return m.RunID() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebasedruncreditallocations.FieldLineID: + return m.OldLineID(ctx) + case chargeusagebasedruncreditallocations.FieldAmount: + return m.OldAmount(ctx) + case chargeusagebasedruncreditallocations.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeusagebasedruncreditallocations.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID: + return m.OldLedgerTransactionGroupID(ctx) + case chargeusagebasedruncreditallocations.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebasedruncreditallocations.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeusagebasedruncreditallocations.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeusagebasedruncreditallocations.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeusagebasedruncreditallocations.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeusagebasedruncreditallocations.FieldRunID: + return m.OldRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebasedruncreditallocations.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeusagebasedruncreditallocations.FieldAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmount(v) + return nil + case chargeusagebasedruncreditallocations.FieldServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodFrom(v) + return nil + case chargeusagebasedruncreditallocations.FieldServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodTo(v) + return nil + case chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLedgerTransactionGroupID(v) + return nil + case chargeusagebasedruncreditallocations.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebasedruncreditallocations.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case chargeusagebasedruncreditallocations.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case chargeusagebasedruncreditallocations.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case chargeusagebasedruncreditallocations.FieldAnnotations: + v, ok := value.(models.Annotations) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnnotations(v) + return nil + case chargeusagebasedruncreditallocations.FieldRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRunID(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebasedruncreditallocations.FieldLineID) { + fields = append(fields, chargeusagebasedruncreditallocations.FieldLineID) + } + if m.FieldCleared(chargeusagebasedruncreditallocations.FieldDeletedAt) { + fields = append(fields, chargeusagebasedruncreditallocations.FieldDeletedAt) + } + if m.FieldCleared(chargeusagebasedruncreditallocations.FieldAnnotations) { + fields = append(fields, chargeusagebasedruncreditallocations.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearField(name string) error { + switch name { + case chargeusagebasedruncreditallocations.FieldLineID: + m.ClearLineID() + return nil + case chargeusagebasedruncreditallocations.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeusagebasedruncreditallocations.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetField(name string) error { + switch name { + case chargeusagebasedruncreditallocations.FieldLineID: + m.ResetLineID() + return nil + case chargeusagebasedruncreditallocations.FieldAmount: + m.ResetAmount() + return nil + case chargeusagebasedruncreditallocations.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeusagebasedruncreditallocations.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeusagebasedruncreditallocations.FieldLedgerTransactionGroupID: + m.ResetLedgerTransactionGroupID() + return nil + case chargeusagebasedruncreditallocations.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebasedruncreditallocations.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeusagebasedruncreditallocations.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeusagebasedruncreditallocations.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeusagebasedruncreditallocations.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeusagebasedruncreditallocations.FieldRunID: + m.ResetRunID() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.run != nil { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedruncreditallocations.EdgeRun: + if id := m.run; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrun { + edges = append(edges, chargeusagebasedruncreditallocations.EdgeRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebasedruncreditallocations.EdgeRun: + return m.clearedrun + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ClearEdge(name string) error { + switch name { + case chargeusagebasedruncreditallocations.EdgeRun: + m.ClearRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ChargeUsageBasedRunCreditAllocationsMutation) ResetEdge(name string) error { + switch name { + case chargeusagebasedruncreditallocations.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunCreditAllocations edge %s", name) +} + +// ChargeUsageBasedRunInvoicedUsageMutation represents an operation that mutates the ChargeUsageBasedRunInvoicedUsage nodes in the graph. +type ChargeUsageBasedRunInvoicedUsageMutation struct { + config + op Op + typ string + id *string + line_id *string + service_period_from *time.Time + service_period_to *time.Time + mutable *bool + ledger_transaction_group_id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + amount *alpacadecimal.Decimal + taxes_total *alpacadecimal.Decimal + taxes_inclusive_total *alpacadecimal.Decimal + taxes_exclusive_total *alpacadecimal.Decimal + charges_total *alpacadecimal.Decimal + discounts_total *alpacadecimal.Decimal + credits_total *alpacadecimal.Decimal + total *alpacadecimal.Decimal + clearedFields map[string]struct{} + run *string + clearedrun bool + done bool + oldValue func(context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) + predicates []predicate.ChargeUsageBasedRunInvoicedUsage +} + +var _ ent.Mutation = (*ChargeUsageBasedRunInvoicedUsageMutation)(nil) + +// chargeusagebasedruninvoicedusageOption allows management of the mutation configuration using functional options. +type chargeusagebasedruninvoicedusageOption func(*ChargeUsageBasedRunInvoicedUsageMutation) + +// newChargeUsageBasedRunInvoicedUsageMutation creates new mutation for the ChargeUsageBasedRunInvoicedUsage entity. +func newChargeUsageBasedRunInvoicedUsageMutation(c config, op Op, opts ...chargeusagebasedruninvoicedusageOption) *ChargeUsageBasedRunInvoicedUsageMutation { + m := &ChargeUsageBasedRunInvoicedUsageMutation{ + config: c, + op: op, + typ: TypeChargeUsageBasedRunInvoicedUsage, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedRunInvoicedUsageID sets the ID field of the mutation. +func withChargeUsageBasedRunInvoicedUsageID(id string) chargeusagebasedruninvoicedusageOption { + return func(m *ChargeUsageBasedRunInvoicedUsageMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBasedRunInvoicedUsage + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBasedRunInvoicedUsage.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBasedRunInvoicedUsage sets the old ChargeUsageBasedRunInvoicedUsage of the mutation. +func withChargeUsageBasedRunInvoicedUsage(node *ChargeUsageBasedRunInvoicedUsage) chargeusagebasedruninvoicedusageOption { + return func(m *ChargeUsageBasedRunInvoicedUsageMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBasedRunInvoicedUsage, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ChargeUsageBasedRunInvoicedUsageMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ChargeUsageBasedRunInvoicedUsageMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ChargeUsageBasedRunInvoicedUsage entities. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetID(id string) { + m.id = &id +} + +// 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 *ChargeUsageBasedRunInvoicedUsageMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + 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 *ChargeUsageBasedRunInvoicedUsageMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ChargeUsageBasedRunInvoicedUsage.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetLineID sets the "line_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetLineID(s string) { + m.line_id = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) LineID() (r string, exists bool) { + v := m.line_id + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldLineID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLineID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLineID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLineID: %w", err) + } + return oldValue.LineID, nil +} + +// ClearLineID clears the value of the "line_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearLineID() { + m.line_id = nil + m.clearedFields[chargeusagebasedruninvoicedusage.FieldLineID] = struct{}{} +} + +// LineIDCleared returns if the "line_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) LineIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruninvoicedusage.FieldLineID] + return ok +} + +// ResetLineID resets all changes to the "line_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetLineID() { + m.line_id = nil + delete(m.clearedFields, chargeusagebasedruninvoicedusage.FieldLineID) +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ServicePeriodFrom() (r time.Time, exists bool) { + v := m.service_period_from + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodFrom returns the old "service_period_from" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodFrom: %w", err) + } + return oldValue.ServicePeriodFrom, nil +} + +// ResetServicePeriodFrom resets all changes to the "service_period_from" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ServicePeriodTo() (r time.Time, exists bool) { + v := m.service_period_to + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodTo returns the old "service_period_to" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodTo: %w", err) + } + return oldValue.ServicePeriodTo, nil +} + +// ResetServicePeriodTo resets all changes to the "service_period_to" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetMutable sets the "mutable" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetMutable(b bool) { + m.mutable = &b +} + +// Mutable returns the value of the "mutable" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Mutable() (r bool, exists bool) { + v := m.mutable + if v == nil { + return + } + return *v, true +} + +// OldMutable returns the old "mutable" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldMutable(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMutable is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMutable requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMutable: %w", err) + } + return oldValue.Mutable, nil +} + +// ResetMutable resets all changes to the "mutable" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetMutable() { + m.mutable = nil +} + +// SetLedgerTransactionGroupID sets the "ledger_transaction_group_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetLedgerTransactionGroupID(s string) { + m.ledger_transaction_group_id = &s +} + +// LedgerTransactionGroupID returns the value of the "ledger_transaction_group_id" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) LedgerTransactionGroupID() (r string, exists bool) { + v := m.ledger_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldLedgerTransactionGroupID returns the old "ledger_transaction_group_id" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldLedgerTransactionGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLedgerTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLedgerTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLedgerTransactionGroupID: %w", err) + } + return oldValue.LedgerTransactionGroupID, nil +} + +// ClearLedgerTransactionGroupID clears the value of the "ledger_transaction_group_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearLedgerTransactionGroupID() { + m.ledger_transaction_group_id = nil + m.clearedFields[chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID] = struct{}{} +} + +// LedgerTransactionGroupIDCleared returns if the "ledger_transaction_group_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) LedgerTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID] + return ok +} + +// ResetLedgerTransactionGroupID resets all changes to the "ledger_transaction_group_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetLedgerTransactionGroupID() { + m.ledger_transaction_group_id = nil + delete(m.clearedFields, chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeusagebasedruninvoicedusage.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruninvoicedusage.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeusagebasedruninvoicedusage.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Annotations() (r models.Annotations, exists bool) { + v := m.annotations + if v == nil { + return + } + return *v, true +} + +// OldAnnotations returns the old "annotations" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldAnnotations(ctx context.Context) (v models.Annotations, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAnnotations is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAnnotations requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAnnotations: %w", err) + } + return oldValue.Annotations, nil +} + +// ClearAnnotations clears the value of the "annotations" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeusagebasedruninvoicedusage.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruninvoicedusage.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeusagebasedruninvoicedusage.FieldAnnotations) +} + +// SetAmount sets the "amount" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Amount() (r alpacadecimal.Decimal, exists bool) { + v := m.amount + if v == nil { + return + } + return *v, true +} + +// OldAmount returns the old "amount" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmount: %w", err) + } + return oldValue.Amount, nil +} + +// ResetAmount resets all changes to the "amount" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetAmount() { + m.amount = nil +} + +// SetTaxesTotal sets the "taxes_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetTaxesTotal(a alpacadecimal.Decimal) { + m.taxes_total = &a +} + +// TaxesTotal returns the value of the "taxes_total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) TaxesTotal() (r alpacadecimal.Decimal, exists bool) { + v := m.taxes_total + if v == nil { + return + } + return *v, true +} + +// OldTaxesTotal returns the old "taxes_total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldTaxesTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxesTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxesTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxesTotal: %w", err) + } + return oldValue.TaxesTotal, nil +} + +// ResetTaxesTotal resets all changes to the "taxes_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetTaxesTotal() { + m.taxes_total = nil +} + +// SetTaxesInclusiveTotal sets the "taxes_inclusive_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetTaxesInclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_inclusive_total = &a +} + +// TaxesInclusiveTotal returns the value of the "taxes_inclusive_total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) TaxesInclusiveTotal() (r alpacadecimal.Decimal, exists bool) { + v := m.taxes_inclusive_total + if v == nil { + return + } + return *v, true +} + +// OldTaxesInclusiveTotal returns the old "taxes_inclusive_total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldTaxesInclusiveTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxesInclusiveTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxesInclusiveTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxesInclusiveTotal: %w", err) + } + return oldValue.TaxesInclusiveTotal, nil +} + +// ResetTaxesInclusiveTotal resets all changes to the "taxes_inclusive_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetTaxesInclusiveTotal() { + m.taxes_inclusive_total = nil +} + +// SetTaxesExclusiveTotal sets the "taxes_exclusive_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetTaxesExclusiveTotal(a alpacadecimal.Decimal) { + m.taxes_exclusive_total = &a +} + +// TaxesExclusiveTotal returns the value of the "taxes_exclusive_total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) TaxesExclusiveTotal() (r alpacadecimal.Decimal, exists bool) { + v := m.taxes_exclusive_total + if v == nil { + return + } + return *v, true +} + +// OldTaxesExclusiveTotal returns the old "taxes_exclusive_total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldTaxesExclusiveTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaxesExclusiveTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaxesExclusiveTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaxesExclusiveTotal: %w", err) + } + return oldValue.TaxesExclusiveTotal, nil +} + +// ResetTaxesExclusiveTotal resets all changes to the "taxes_exclusive_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetTaxesExclusiveTotal() { + m.taxes_exclusive_total = nil +} + +// SetChargesTotal sets the "charges_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetChargesTotal(a alpacadecimal.Decimal) { + m.charges_total = &a +} + +// ChargesTotal returns the value of the "charges_total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ChargesTotal() (r alpacadecimal.Decimal, exists bool) { + v := m.charges_total + if v == nil { + return + } + return *v, true +} + +// OldChargesTotal returns the old "charges_total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldChargesTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChargesTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChargesTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChargesTotal: %w", err) + } + return oldValue.ChargesTotal, nil +} + +// ResetChargesTotal resets all changes to the "charges_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetChargesTotal() { + m.charges_total = nil +} + +// SetDiscountsTotal sets the "discounts_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetDiscountsTotal(a alpacadecimal.Decimal) { + m.discounts_total = &a +} + +// DiscountsTotal returns the value of the "discounts_total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) DiscountsTotal() (r alpacadecimal.Decimal, exists bool) { + v := m.discounts_total + if v == nil { + return + } + return *v, true +} + +// OldDiscountsTotal returns the old "discounts_total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldDiscountsTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDiscountsTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDiscountsTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDiscountsTotal: %w", err) + } + return oldValue.DiscountsTotal, nil +} + +// ResetDiscountsTotal resets all changes to the "discounts_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetDiscountsTotal() { + m.discounts_total = nil +} + +// SetCreditsTotal sets the "credits_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetCreditsTotal(a alpacadecimal.Decimal) { + m.credits_total = &a +} + +// CreditsTotal returns the value of the "credits_total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) CreditsTotal() (r alpacadecimal.Decimal, exists bool) { + v := m.credits_total + if v == nil { + return + } + return *v, true +} + +// OldCreditsTotal returns the old "credits_total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldCreditsTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreditsTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreditsTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreditsTotal: %w", err) + } + return oldValue.CreditsTotal, nil +} + +// ResetCreditsTotal resets all changes to the "credits_total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetCreditsTotal() { + m.credits_total = nil +} + +// SetTotal sets the "total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetTotal(a alpacadecimal.Decimal) { + m.total = &a +} + +// Total returns the value of the "total" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Total() (r alpacadecimal.Decimal, exists bool) { + v := m.total + if v == nil { + return + } + return *v, true +} + +// OldTotal returns the old "total" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldTotal(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotal: %w", err) + } + return oldValue.Total, nil +} + +// ResetTotal resets all changes to the "total" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetTotal() { + m.total = nil +} + +// SetRunID sets the "run_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) RunID() (r string, exists bool) { + v := m.run + if v == nil { + return + } + return *v, true +} + +// OldRunID returns the old "run_id" field's value of the ChargeUsageBasedRunInvoicedUsage entity. +// If the ChargeUsageBasedRunInvoicedUsage object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldRunID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRunID: %w", err) + } + return oldValue.RunID, nil +} + +// ResetRunID resets all changes to the "run_id" field. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetRunID() { + m.run = nil +} + +// ClearRun clears the "run" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeusagebasedruninvoicedusage.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) RunCleared() bool { + return m.clearedrun +} + +// RunIDs returns the "run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RunID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// Where appends a list predicates to the ChargeUsageBasedRunInvoicedUsageMutation builder. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Where(ps ...predicate.ChargeUsageBasedRunInvoicedUsage) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedRunInvoicedUsageMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBasedRunInvoicedUsage, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBasedRunInvoicedUsage). +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Fields() []string { + fields := make([]string, 0, 19) + if m.line_id != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldLineID) + } + if m.service_period_from != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldServicePeriodTo) + } + if m.mutable != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldMutable) + } + if m.ledger_transaction_group_id != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID) + } + if m.namespace != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldAnnotations) + } + if m.amount != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldAmount) + } + if m.taxes_total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldTaxesTotal) + } + if m.taxes_inclusive_total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal) + } + if m.taxes_exclusive_total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal) + } + if m.charges_total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldChargesTotal) + } + if m.discounts_total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldDiscountsTotal) + } + if m.credits_total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldCreditsTotal) + } + if m.total != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldTotal) + } + if m.run != nil { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldRunID) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedruninvoicedusage.FieldLineID: + return m.LineID() + case chargeusagebasedruninvoicedusage.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeusagebasedruninvoicedusage.FieldMutable: + return m.Mutable() + case chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID: + return m.LedgerTransactionGroupID() + case chargeusagebasedruninvoicedusage.FieldNamespace: + return m.Namespace() + case chargeusagebasedruninvoicedusage.FieldCreatedAt: + return m.CreatedAt() + case chargeusagebasedruninvoicedusage.FieldUpdatedAt: + return m.UpdatedAt() + case chargeusagebasedruninvoicedusage.FieldDeletedAt: + return m.DeletedAt() + case chargeusagebasedruninvoicedusage.FieldAnnotations: + return m.Annotations() + case chargeusagebasedruninvoicedusage.FieldAmount: + return m.Amount() + case chargeusagebasedruninvoicedusage.FieldTaxesTotal: + return m.TaxesTotal() + case chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal: + return m.TaxesInclusiveTotal() + case chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal: + return m.TaxesExclusiveTotal() + case chargeusagebasedruninvoicedusage.FieldChargesTotal: + return m.ChargesTotal() + case chargeusagebasedruninvoicedusage.FieldDiscountsTotal: + return m.DiscountsTotal() + case chargeusagebasedruninvoicedusage.FieldCreditsTotal: + return m.CreditsTotal() + case chargeusagebasedruninvoicedusage.FieldTotal: + return m.Total() + case chargeusagebasedruninvoicedusage.FieldRunID: + return m.RunID() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebasedruninvoicedusage.FieldLineID: + return m.OldLineID(ctx) + case chargeusagebasedruninvoicedusage.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeusagebasedruninvoicedusage.FieldMutable: + return m.OldMutable(ctx) + case chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID: + return m.OldLedgerTransactionGroupID(ctx) + case chargeusagebasedruninvoicedusage.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebasedruninvoicedusage.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeusagebasedruninvoicedusage.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeusagebasedruninvoicedusage.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeusagebasedruninvoicedusage.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeusagebasedruninvoicedusage.FieldAmount: + return m.OldAmount(ctx) + case chargeusagebasedruninvoicedusage.FieldTaxesTotal: + return m.OldTaxesTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal: + return m.OldTaxesInclusiveTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal: + return m.OldTaxesExclusiveTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldChargesTotal: + return m.OldChargesTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldDiscountsTotal: + return m.OldDiscountsTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldCreditsTotal: + return m.OldCreditsTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldTotal: + return m.OldTotal(ctx) + case chargeusagebasedruninvoicedusage.FieldRunID: + return m.OldRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebasedruninvoicedusage.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeusagebasedruninvoicedusage.FieldServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodFrom(v) + return nil + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodTo(v) + return nil + case chargeusagebasedruninvoicedusage.FieldMutable: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMutable(v) + return nil + case chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLedgerTransactionGroupID(v) + return nil + case chargeusagebasedruninvoicedusage.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebasedruninvoicedusage.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case chargeusagebasedruninvoicedusage.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case chargeusagebasedruninvoicedusage.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case chargeusagebasedruninvoicedusage.FieldAnnotations: + v, ok := value.(models.Annotations) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnnotations(v) + return nil + case chargeusagebasedruninvoicedusage.FieldAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmount(v) + return nil + case chargeusagebasedruninvoicedusage.FieldTaxesTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxesTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxesInclusiveTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaxesExclusiveTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldChargesTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargesTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldDiscountsTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDiscountsTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldCreditsTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreditsTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldTotal: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotal(v) + return nil + case chargeusagebasedruninvoicedusage.FieldRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRunID(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebasedruninvoicedusage.FieldLineID) { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldLineID) + } + if m.FieldCleared(chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID) { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID) + } + if m.FieldCleared(chargeusagebasedruninvoicedusage.FieldDeletedAt) { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldDeletedAt) + } + if m.FieldCleared(chargeusagebasedruninvoicedusage.FieldAnnotations) { + fields = append(fields, chargeusagebasedruninvoicedusage.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearField(name string) error { + switch name { + case chargeusagebasedruninvoicedusage.FieldLineID: + m.ClearLineID() + return nil + case chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID: + m.ClearLedgerTransactionGroupID() + return nil + case chargeusagebasedruninvoicedusage.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeusagebasedruninvoicedusage.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetField(name string) error { + switch name { + case chargeusagebasedruninvoicedusage.FieldLineID: + m.ResetLineID() + return nil + case chargeusagebasedruninvoicedusage.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeusagebasedruninvoicedusage.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeusagebasedruninvoicedusage.FieldMutable: + m.ResetMutable() + return nil + case chargeusagebasedruninvoicedusage.FieldLedgerTransactionGroupID: + m.ResetLedgerTransactionGroupID() + return nil + case chargeusagebasedruninvoicedusage.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebasedruninvoicedusage.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeusagebasedruninvoicedusage.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeusagebasedruninvoicedusage.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeusagebasedruninvoicedusage.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeusagebasedruninvoicedusage.FieldAmount: + m.ResetAmount() + return nil + case chargeusagebasedruninvoicedusage.FieldTaxesTotal: + m.ResetTaxesTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldTaxesInclusiveTotal: + m.ResetTaxesInclusiveTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldTaxesExclusiveTotal: + m.ResetTaxesExclusiveTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldChargesTotal: + m.ResetChargesTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldDiscountsTotal: + m.ResetDiscountsTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldCreditsTotal: + m.ResetCreditsTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldTotal: + m.ResetTotal() + return nil + case chargeusagebasedruninvoicedusage.FieldRunID: + m.ResetRunID() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.run != nil { + edges = append(edges, chargeusagebasedruninvoicedusage.EdgeRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedruninvoicedusage.EdgeRun: + if id := m.run; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrun { + edges = append(edges, chargeusagebasedruninvoicedusage.EdgeRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebasedruninvoicedusage.EdgeRun: + return m.clearedrun + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ClearEdge(name string) error { + switch name { + case chargeusagebasedruninvoicedusage.EdgeRun: + m.ClearRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ChargeUsageBasedRunInvoicedUsageMutation) ResetEdge(name string) error { + switch name { + case chargeusagebasedruninvoicedusage.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunInvoicedUsage edge %s", name) +} + +// ChargeUsageBasedRunPaymentMutation represents an operation that mutates the ChargeUsageBasedRunPayment nodes in the graph. +type ChargeUsageBasedRunPaymentMutation struct { + config + op Op + typ string + id *string + line_id *string + service_period_from *time.Time + service_period_to *time.Time + status *payment.Status + amount *alpacadecimal.Decimal + authorized_transaction_group_id *string + authorized_at *time.Time + settled_transaction_group_id *string + settled_at *time.Time + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + annotations *models.Annotations + clearedFields map[string]struct{} + run *string + clearedrun bool + done bool + oldValue func(context.Context) (*ChargeUsageBasedRunPayment, error) + predicates []predicate.ChargeUsageBasedRunPayment +} + +var _ ent.Mutation = (*ChargeUsageBasedRunPaymentMutation)(nil) + +// chargeusagebasedrunpaymentOption allows management of the mutation configuration using functional options. +type chargeusagebasedrunpaymentOption func(*ChargeUsageBasedRunPaymentMutation) + +// newChargeUsageBasedRunPaymentMutation creates new mutation for the ChargeUsageBasedRunPayment entity. +func newChargeUsageBasedRunPaymentMutation(c config, op Op, opts ...chargeusagebasedrunpaymentOption) *ChargeUsageBasedRunPaymentMutation { + m := &ChargeUsageBasedRunPaymentMutation{ + config: c, + op: op, + typ: TypeChargeUsageBasedRunPayment, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedRunPaymentID sets the ID field of the mutation. +func withChargeUsageBasedRunPaymentID(id string) chargeusagebasedrunpaymentOption { + return func(m *ChargeUsageBasedRunPaymentMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBasedRunPayment + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBasedRunPayment, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBasedRunPayment.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBasedRunPayment sets the old ChargeUsageBasedRunPayment of the mutation. +func withChargeUsageBasedRunPayment(node *ChargeUsageBasedRunPayment) chargeusagebasedrunpaymentOption { + return func(m *ChargeUsageBasedRunPaymentMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBasedRunPayment, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ChargeUsageBasedRunPaymentMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ChargeUsageBasedRunPaymentMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ChargeUsageBasedRunPayment entities. +func (m *ChargeUsageBasedRunPaymentMutation) SetID(id string) { + m.id = &id +} + +// 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 *ChargeUsageBasedRunPaymentMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + 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 *ChargeUsageBasedRunPaymentMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ChargeUsageBasedRunPayment.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetLineID sets the "line_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetLineID(s string) { + m.line_id = &s +} + +// LineID returns the value of the "line_id" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) LineID() (r string, exists bool) { + v := m.line_id + if v == nil { + return + } + return *v, true +} + +// OldLineID returns the old "line_id" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldLineID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLineID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLineID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLineID: %w", err) + } + return oldValue.LineID, nil +} + +// ResetLineID resets all changes to the "line_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetLineID() { + m.line_id = nil +} + +// SetServicePeriodFrom sets the "service_period_from" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetServicePeriodFrom(t time.Time) { + m.service_period_from = &t +} + +// ServicePeriodFrom returns the value of the "service_period_from" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) ServicePeriodFrom() (r time.Time, exists bool) { + v := m.service_period_from + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodFrom returns the old "service_period_from" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldServicePeriodFrom(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodFrom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodFrom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodFrom: %w", err) + } + return oldValue.ServicePeriodFrom, nil +} + +// ResetServicePeriodFrom resets all changes to the "service_period_from" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetServicePeriodFrom() { + m.service_period_from = nil +} + +// SetServicePeriodTo sets the "service_period_to" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetServicePeriodTo(t time.Time) { + m.service_period_to = &t +} + +// ServicePeriodTo returns the value of the "service_period_to" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) ServicePeriodTo() (r time.Time, exists bool) { + v := m.service_period_to + if v == nil { + return + } + return *v, true +} + +// OldServicePeriodTo returns the old "service_period_to" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldServicePeriodTo(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServicePeriodTo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServicePeriodTo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServicePeriodTo: %w", err) + } + return oldValue.ServicePeriodTo, nil +} + +// ResetServicePeriodTo resets all changes to the "service_period_to" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetServicePeriodTo() { + m.service_period_to = nil +} + +// SetStatus sets the "status" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetStatus(pa payment.Status) { + m.status = &pa +} + +// Status returns the value of the "status" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) Status() (r payment.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldStatus(ctx context.Context) (v payment.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetStatus() { + m.status = nil +} + +// SetAmount sets the "amount" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetAmount(a alpacadecimal.Decimal) { + m.amount = &a +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) Amount() (r alpacadecimal.Decimal, exists bool) { + v := m.amount + if v == nil { + return + } + return *v, true +} + +// OldAmount returns the old "amount" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldAmount(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmount: %w", err) + } + return oldValue.Amount, nil +} + +// ResetAmount resets all changes to the "amount" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetAmount() { + m.amount = nil +} + +// SetAuthorizedTransactionGroupID sets the "authorized_transaction_group_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetAuthorizedTransactionGroupID(s string) { + m.authorized_transaction_group_id = &s +} + +// AuthorizedTransactionGroupID returns the value of the "authorized_transaction_group_id" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AuthorizedTransactionGroupID() (r string, exists bool) { + v := m.authorized_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldAuthorizedTransactionGroupID returns the old "authorized_transaction_group_id" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldAuthorizedTransactionGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorizedTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorizedTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorizedTransactionGroupID: %w", err) + } + return oldValue.AuthorizedTransactionGroupID, nil +} + +// ClearAuthorizedTransactionGroupID clears the value of the "authorized_transaction_group_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ClearAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + m.clearedFields[chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID] = struct{}{} +} + +// AuthorizedTransactionGroupIDCleared returns if the "authorized_transaction_group_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AuthorizedTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID] + return ok +} + +// ResetAuthorizedTransactionGroupID resets all changes to the "authorized_transaction_group_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetAuthorizedTransactionGroupID() { + m.authorized_transaction_group_id = nil + delete(m.clearedFields, chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID) +} + +// SetAuthorizedAt sets the "authorized_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetAuthorizedAt(t time.Time) { + m.authorized_at = &t +} + +// AuthorizedAt returns the value of the "authorized_at" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AuthorizedAt() (r time.Time, exists bool) { + v := m.authorized_at + if v == nil { + return + } + return *v, true +} + +// OldAuthorizedAt returns the old "authorized_at" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldAuthorizedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorizedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorizedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorizedAt: %w", err) + } + return oldValue.AuthorizedAt, nil +} + +// ClearAuthorizedAt clears the value of the "authorized_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ClearAuthorizedAt() { + m.authorized_at = nil + m.clearedFields[chargeusagebasedrunpayment.FieldAuthorizedAt] = struct{}{} +} + +// AuthorizedAtCleared returns if the "authorized_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AuthorizedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrunpayment.FieldAuthorizedAt] + return ok +} + +// ResetAuthorizedAt resets all changes to the "authorized_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetAuthorizedAt() { + m.authorized_at = nil + delete(m.clearedFields, chargeusagebasedrunpayment.FieldAuthorizedAt) +} + +// SetSettledTransactionGroupID sets the "settled_transaction_group_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetSettledTransactionGroupID(s string) { + m.settled_transaction_group_id = &s +} + +// SettledTransactionGroupID returns the value of the "settled_transaction_group_id" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) SettledTransactionGroupID() (r string, exists bool) { + v := m.settled_transaction_group_id + if v == nil { + return + } + return *v, true +} + +// OldSettledTransactionGroupID returns the old "settled_transaction_group_id" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldSettledTransactionGroupID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSettledTransactionGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSettledTransactionGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSettledTransactionGroupID: %w", err) + } + return oldValue.SettledTransactionGroupID, nil +} + +// ClearSettledTransactionGroupID clears the value of the "settled_transaction_group_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ClearSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + m.clearedFields[chargeusagebasedrunpayment.FieldSettledTransactionGroupID] = struct{}{} +} + +// SettledTransactionGroupIDCleared returns if the "settled_transaction_group_id" field was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) SettledTransactionGroupIDCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrunpayment.FieldSettledTransactionGroupID] + return ok +} + +// ResetSettledTransactionGroupID resets all changes to the "settled_transaction_group_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetSettledTransactionGroupID() { + m.settled_transaction_group_id = nil + delete(m.clearedFields, chargeusagebasedrunpayment.FieldSettledTransactionGroupID) +} + +// SetSettledAt sets the "settled_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetSettledAt(t time.Time) { + m.settled_at = &t +} + +// SettledAt returns the value of the "settled_at" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) SettledAt() (r time.Time, exists bool) { + v := m.settled_at + if v == nil { + return + } + return *v, true +} + +// OldSettledAt returns the old "settled_at" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldSettledAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSettledAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSettledAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSettledAt: %w", err) + } + return oldValue.SettledAt, nil +} + +// ClearSettledAt clears the value of the "settled_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ClearSettledAt() { + m.settled_at = nil + m.clearedFields[chargeusagebasedrunpayment.FieldSettledAt] = struct{}{} +} + +// SettledAtCleared returns if the "settled_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) SettledAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrunpayment.FieldSettledAt] + return ok +} + +// ResetSettledAt resets all changes to the "settled_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetSettledAt() { + m.settled_at = nil + delete(m.clearedFields, chargeusagebasedrunpayment.FieldSettledAt) +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeusagebasedrunpayment.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrunpayment.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeusagebasedrunpayment.FieldDeletedAt) +} + +// SetAnnotations sets the "annotations" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetAnnotations(value models.Annotations) { + m.annotations = &value +} + +// Annotations returns the value of the "annotations" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) Annotations() (r models.Annotations, exists bool) { + v := m.annotations + if v == nil { + return + } + return *v, true +} + +// OldAnnotations returns the old "annotations" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldAnnotations(ctx context.Context) (v models.Annotations, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAnnotations is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAnnotations requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAnnotations: %w", err) + } + return oldValue.Annotations, nil +} + +// ClearAnnotations clears the value of the "annotations" field. +func (m *ChargeUsageBasedRunPaymentMutation) ClearAnnotations() { + m.annotations = nil + m.clearedFields[chargeusagebasedrunpayment.FieldAnnotations] = struct{}{} +} + +// AnnotationsCleared returns if the "annotations" field was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AnnotationsCleared() bool { + _, ok := m.clearedFields[chargeusagebasedrunpayment.FieldAnnotations] + return ok +} + +// ResetAnnotations resets all changes to the "annotations" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetAnnotations() { + m.annotations = nil + delete(m.clearedFields, chargeusagebasedrunpayment.FieldAnnotations) +} + +// SetRunID sets the "run_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) SetRunID(s string) { + m.run = &s +} + +// RunID returns the value of the "run_id" field in the mutation. +func (m *ChargeUsageBasedRunPaymentMutation) RunID() (r string, exists bool) { + v := m.run + if v == nil { + return + } + return *v, true +} + +// OldRunID returns the old "run_id" field's value of the ChargeUsageBasedRunPayment entity. +// If the ChargeUsageBasedRunPayment object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunPaymentMutation) OldRunID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRunID: %w", err) + } + return oldValue.RunID, nil +} + +// ResetRunID resets all changes to the "run_id" field. +func (m *ChargeUsageBasedRunPaymentMutation) ResetRunID() { + m.run = nil +} + +// ClearRun clears the "run" edge to the ChargeUsageBasedRuns entity. +func (m *ChargeUsageBasedRunPaymentMutation) ClearRun() { + m.clearedrun = true + m.clearedFields[chargeusagebasedrunpayment.FieldRunID] = struct{}{} +} + +// RunCleared reports if the "run" edge to the ChargeUsageBasedRuns entity was cleared. +func (m *ChargeUsageBasedRunPaymentMutation) RunCleared() bool { + return m.clearedrun +} + +// RunIDs returns the "run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RunID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunPaymentMutation) RunIDs() (ids []string) { + if id := m.run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRun resets all changes to the "run" edge. +func (m *ChargeUsageBasedRunPaymentMutation) ResetRun() { + m.run = nil + m.clearedrun = false +} + +// Where appends a list predicates to the ChargeUsageBasedRunPaymentMutation builder. +func (m *ChargeUsageBasedRunPaymentMutation) Where(ps ...predicate.ChargeUsageBasedRunPayment) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedRunPaymentMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedRunPaymentMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBasedRunPayment, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedRunPaymentMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedRunPaymentMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBasedRunPayment). +func (m *ChargeUsageBasedRunPaymentMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ChargeUsageBasedRunPaymentMutation) Fields() []string { + fields := make([]string, 0, 15) + if m.line_id != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldLineID) + } + if m.service_period_from != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldServicePeriodFrom) + } + if m.service_period_to != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldServicePeriodTo) + } + if m.status != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldStatus) + } + if m.amount != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldAmount) + } + if m.authorized_transaction_group_id != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID) + } + if m.authorized_at != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldAuthorizedAt) + } + if m.settled_transaction_group_id != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldSettledTransactionGroupID) + } + if m.settled_at != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldSettledAt) + } + if m.namespace != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldDeletedAt) + } + if m.annotations != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldAnnotations) + } + if m.run != nil { + fields = append(fields, chargeusagebasedrunpayment.FieldRunID) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ChargeUsageBasedRunPaymentMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedrunpayment.FieldLineID: + return m.LineID() + case chargeusagebasedrunpayment.FieldServicePeriodFrom: + return m.ServicePeriodFrom() + case chargeusagebasedrunpayment.FieldServicePeriodTo: + return m.ServicePeriodTo() + case chargeusagebasedrunpayment.FieldStatus: + return m.Status() + case chargeusagebasedrunpayment.FieldAmount: + return m.Amount() + case chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID: + return m.AuthorizedTransactionGroupID() + case chargeusagebasedrunpayment.FieldAuthorizedAt: + return m.AuthorizedAt() + case chargeusagebasedrunpayment.FieldSettledTransactionGroupID: + return m.SettledTransactionGroupID() + case chargeusagebasedrunpayment.FieldSettledAt: + return m.SettledAt() + case chargeusagebasedrunpayment.FieldNamespace: + return m.Namespace() + case chargeusagebasedrunpayment.FieldCreatedAt: + return m.CreatedAt() + case chargeusagebasedrunpayment.FieldUpdatedAt: + return m.UpdatedAt() + case chargeusagebasedrunpayment.FieldDeletedAt: + return m.DeletedAt() + case chargeusagebasedrunpayment.FieldAnnotations: + return m.Annotations() + case chargeusagebasedrunpayment.FieldRunID: + return m.RunID() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ChargeUsageBasedRunPaymentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebasedrunpayment.FieldLineID: + return m.OldLineID(ctx) + case chargeusagebasedrunpayment.FieldServicePeriodFrom: + return m.OldServicePeriodFrom(ctx) + case chargeusagebasedrunpayment.FieldServicePeriodTo: + return m.OldServicePeriodTo(ctx) + case chargeusagebasedrunpayment.FieldStatus: + return m.OldStatus(ctx) + case chargeusagebasedrunpayment.FieldAmount: + return m.OldAmount(ctx) + case chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID: + return m.OldAuthorizedTransactionGroupID(ctx) + case chargeusagebasedrunpayment.FieldAuthorizedAt: + return m.OldAuthorizedAt(ctx) + case chargeusagebasedrunpayment.FieldSettledTransactionGroupID: + return m.OldSettledTransactionGroupID(ctx) + case chargeusagebasedrunpayment.FieldSettledAt: + return m.OldSettledAt(ctx) + case chargeusagebasedrunpayment.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebasedrunpayment.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeusagebasedrunpayment.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeusagebasedrunpayment.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeusagebasedrunpayment.FieldAnnotations: + return m.OldAnnotations(ctx) + case chargeusagebasedrunpayment.FieldRunID: + return m.OldRunID(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBasedRunPayment field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunPaymentMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebasedrunpayment.FieldLineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLineID(v) + return nil + case chargeusagebasedrunpayment.FieldServicePeriodFrom: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodFrom(v) + return nil + case chargeusagebasedrunpayment.FieldServicePeriodTo: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServicePeriodTo(v) + return nil + case chargeusagebasedrunpayment.FieldStatus: + v, ok := value.(payment.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case chargeusagebasedrunpayment.FieldAmount: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmount(v) + return nil + case chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorizedTransactionGroupID(v) + return nil + case chargeusagebasedrunpayment.FieldAuthorizedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorizedAt(v) + return nil + case chargeusagebasedrunpayment.FieldSettledTransactionGroupID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettledTransactionGroupID(v) + return nil + case chargeusagebasedrunpayment.FieldSettledAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettledAt(v) + return nil + case chargeusagebasedrunpayment.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebasedrunpayment.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case chargeusagebasedrunpayment.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case chargeusagebasedrunpayment.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case chargeusagebasedrunpayment.FieldAnnotations: + v, ok := value.(models.Annotations) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAnnotations(v) + return nil + case chargeusagebasedrunpayment.FieldRunID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRunID(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunPayment field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ChargeUsageBasedRunPaymentMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunPaymentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeUsageBasedRunPayment numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedRunPaymentMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID) { + fields = append(fields, chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID) + } + if m.FieldCleared(chargeusagebasedrunpayment.FieldAuthorizedAt) { + fields = append(fields, chargeusagebasedrunpayment.FieldAuthorizedAt) + } + if m.FieldCleared(chargeusagebasedrunpayment.FieldSettledTransactionGroupID) { + fields = append(fields, chargeusagebasedrunpayment.FieldSettledTransactionGroupID) + } + if m.FieldCleared(chargeusagebasedrunpayment.FieldSettledAt) { + fields = append(fields, chargeusagebasedrunpayment.FieldSettledAt) + } + if m.FieldCleared(chargeusagebasedrunpayment.FieldDeletedAt) { + fields = append(fields, chargeusagebasedrunpayment.FieldDeletedAt) + } + if m.FieldCleared(chargeusagebasedrunpayment.FieldAnnotations) { + fields = append(fields, chargeusagebasedrunpayment.FieldAnnotations) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunPaymentMutation) ClearField(name string) error { + switch name { + case chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID: + m.ClearAuthorizedTransactionGroupID() + return nil + case chargeusagebasedrunpayment.FieldAuthorizedAt: + m.ClearAuthorizedAt() + return nil + case chargeusagebasedrunpayment.FieldSettledTransactionGroupID: + m.ClearSettledTransactionGroupID() + return nil + case chargeusagebasedrunpayment.FieldSettledAt: + m.ClearSettledAt() + return nil + case chargeusagebasedrunpayment.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case chargeusagebasedrunpayment.FieldAnnotations: + m.ClearAnnotations() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunPayment nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunPaymentMutation) ResetField(name string) error { + switch name { + case chargeusagebasedrunpayment.FieldLineID: + m.ResetLineID() + return nil + case chargeusagebasedrunpayment.FieldServicePeriodFrom: + m.ResetServicePeriodFrom() + return nil + case chargeusagebasedrunpayment.FieldServicePeriodTo: + m.ResetServicePeriodTo() + return nil + case chargeusagebasedrunpayment.FieldStatus: + m.ResetStatus() + return nil + case chargeusagebasedrunpayment.FieldAmount: + m.ResetAmount() + return nil + case chargeusagebasedrunpayment.FieldAuthorizedTransactionGroupID: + m.ResetAuthorizedTransactionGroupID() + return nil + case chargeusagebasedrunpayment.FieldAuthorizedAt: + m.ResetAuthorizedAt() + return nil + case chargeusagebasedrunpayment.FieldSettledTransactionGroupID: + m.ResetSettledTransactionGroupID() + return nil + case chargeusagebasedrunpayment.FieldSettledAt: + m.ResetSettledAt() + return nil + case chargeusagebasedrunpayment.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebasedrunpayment.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeusagebasedrunpayment.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeusagebasedrunpayment.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeusagebasedrunpayment.FieldAnnotations: + m.ResetAnnotations() + return nil + case chargeusagebasedrunpayment.FieldRunID: + m.ResetRunID() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunPayment field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.run != nil { + edges = append(edges, chargeusagebasedrunpayment.EdgeRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedrunpayment.EdgeRun: + if id := m.run; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrun { + edges = append(edges, chargeusagebasedrunpayment.EdgeRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedRunPaymentMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebasedrunpayment.EdgeRun: + return m.clearedrun + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ChargeUsageBasedRunPaymentMutation) ClearEdge(name string) error { + switch name { + case chargeusagebasedrunpayment.EdgeRun: + m.ClearRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunPayment unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ChargeUsageBasedRunPaymentMutation) ResetEdge(name string) error { + switch name { + case chargeusagebasedrunpayment.EdgeRun: + m.ResetRun() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRunPayment edge %s", name) +} + +// ChargeUsageBasedRunsMutation represents an operation that mutates the ChargeUsageBasedRuns nodes in the graph. +type ChargeUsageBasedRunsMutation struct { + config + op Op + typ string + id *string + namespace *string + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + _type *usagebased.RealizationRunType + asof *time.Time + meter_value *alpacadecimal.Decimal + clearedFields map[string]struct{} + usage_based *string + clearedusage_based bool + credit_allocations map[string]struct{} + removedcredit_allocations map[string]struct{} + clearedcredit_allocations bool + invoiced_usage *string + clearedinvoiced_usage bool + payment *string + clearedpayment bool + done bool + oldValue func(context.Context) (*ChargeUsageBasedRuns, error) + predicates []predicate.ChargeUsageBasedRuns +} + +var _ ent.Mutation = (*ChargeUsageBasedRunsMutation)(nil) + +// chargeusagebasedrunsOption allows management of the mutation configuration using functional options. +type chargeusagebasedrunsOption func(*ChargeUsageBasedRunsMutation) + +// newChargeUsageBasedRunsMutation creates new mutation for the ChargeUsageBasedRuns entity. +func newChargeUsageBasedRunsMutation(c config, op Op, opts ...chargeusagebasedrunsOption) *ChargeUsageBasedRunsMutation { + m := &ChargeUsageBasedRunsMutation{ + config: c, + op: op, + typ: TypeChargeUsageBasedRuns, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withChargeUsageBasedRunsID sets the ID field of the mutation. +func withChargeUsageBasedRunsID(id string) chargeusagebasedrunsOption { + return func(m *ChargeUsageBasedRunsMutation) { + var ( + err error + once sync.Once + value *ChargeUsageBasedRuns + ) + m.oldValue = func(ctx context.Context) (*ChargeUsageBasedRuns, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ChargeUsageBasedRuns.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withChargeUsageBasedRuns sets the old ChargeUsageBasedRuns of the mutation. +func withChargeUsageBasedRuns(node *ChargeUsageBasedRuns) chargeusagebasedrunsOption { + return func(m *ChargeUsageBasedRunsMutation) { + m.oldValue = func(context.Context) (*ChargeUsageBasedRuns, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ChargeUsageBasedRunsMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ChargeUsageBasedRunsMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ChargeUsageBasedRuns entities. +func (m *ChargeUsageBasedRunsMutation) SetID(id string) { + m.id = &id +} + +// 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 *ChargeUsageBasedRunsMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + 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 *ChargeUsageBasedRunsMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ChargeUsageBasedRuns.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetNamespace sets the "namespace" field. +func (m *ChargeUsageBasedRunsMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *ChargeUsageBasedRunsMutation) ResetNamespace() { + m.namespace = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ChargeUsageBasedRunsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ChargeUsageBasedRunsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ChargeUsageBasedRunsMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ChargeUsageBasedRunsMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ChargeUsageBasedRunsMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *ChargeUsageBasedRunsMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[chargeusagebasedruns.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ChargeUsageBasedRunsMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[chargeusagebasedruns.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ChargeUsageBasedRunsMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, chargeusagebasedruns.FieldDeletedAt) +} + +// SetChargeID sets the "charge_id" field. +func (m *ChargeUsageBasedRunsMutation) SetChargeID(s string) { + m.usage_based = &s +} + +// ChargeID returns the value of the "charge_id" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) ChargeID() (r string, exists bool) { + v := m.usage_based + if v == nil { + return + } + return *v, true +} + +// OldChargeID returns the old "charge_id" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldChargeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChargeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChargeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChargeID: %w", err) + } + return oldValue.ChargeID, nil +} + +// ResetChargeID resets all changes to the "charge_id" field. +func (m *ChargeUsageBasedRunsMutation) ResetChargeID() { + m.usage_based = nil +} + +// SetType sets the "type" field. +func (m *ChargeUsageBasedRunsMutation) SetType(urt usagebased.RealizationRunType) { + m._type = &urt +} + +// GetType returns the value of the "type" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) GetType() (r usagebased.RealizationRunType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldType(ctx context.Context) (v usagebased.RealizationRunType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// ResetType resets all changes to the "type" field. +func (m *ChargeUsageBasedRunsMutation) ResetType() { + m._type = nil +} + +// SetAsof sets the "asof" field. +func (m *ChargeUsageBasedRunsMutation) SetAsof(t time.Time) { + m.asof = &t +} + +// Asof returns the value of the "asof" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) Asof() (r time.Time, exists bool) { + v := m.asof + if v == nil { + return + } + return *v, true +} + +// OldAsof returns the old "asof" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldAsof(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAsof is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAsof requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAsof: %w", err) + } + return oldValue.Asof, nil +} + +// ResetAsof resets all changes to the "asof" field. +func (m *ChargeUsageBasedRunsMutation) ResetAsof() { + m.asof = nil +} + +// SetMeterValue sets the "meter_value" field. +func (m *ChargeUsageBasedRunsMutation) SetMeterValue(a alpacadecimal.Decimal) { + m.meter_value = &a +} + +// MeterValue returns the value of the "meter_value" field in the mutation. +func (m *ChargeUsageBasedRunsMutation) MeterValue() (r alpacadecimal.Decimal, exists bool) { + v := m.meter_value + if v == nil { + return + } + return *v, true +} + +// OldMeterValue returns the old "meter_value" field's value of the ChargeUsageBasedRuns entity. +// If the ChargeUsageBasedRuns object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ChargeUsageBasedRunsMutation) OldMeterValue(ctx context.Context) (v alpacadecimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMeterValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMeterValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMeterValue: %w", err) + } + return oldValue.MeterValue, nil +} + +// ResetMeterValue resets all changes to the "meter_value" field. +func (m *ChargeUsageBasedRunsMutation) ResetMeterValue() { + m.meter_value = nil +} + +// SetUsageBasedID sets the "usage_based" edge to the ChargeUsageBased entity by id. +func (m *ChargeUsageBasedRunsMutation) SetUsageBasedID(id string) { + m.usage_based = &id +} + +// ClearUsageBased clears the "usage_based" edge to the ChargeUsageBased entity. +func (m *ChargeUsageBasedRunsMutation) ClearUsageBased() { + m.clearedusage_based = true + m.clearedFields[chargeusagebasedruns.FieldChargeID] = struct{}{} +} + +// UsageBasedCleared reports if the "usage_based" edge to the ChargeUsageBased entity was cleared. +func (m *ChargeUsageBasedRunsMutation) UsageBasedCleared() bool { + return m.clearedusage_based +} + +// UsageBasedID returns the "usage_based" edge ID in the mutation. +func (m *ChargeUsageBasedRunsMutation) UsageBasedID() (id string, exists bool) { + if m.usage_based != nil { + return *m.usage_based, true + } + return +} + +// UsageBasedIDs returns the "usage_based" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UsageBasedID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunsMutation) UsageBasedIDs() (ids []string) { + if id := m.usage_based; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUsageBased resets all changes to the "usage_based" edge. +func (m *ChargeUsageBasedRunsMutation) ResetUsageBased() { + m.usage_based = nil + m.clearedusage_based = false +} + +// AddCreditAllocationIDs adds the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity by ids. +func (m *ChargeUsageBasedRunsMutation) AddCreditAllocationIDs(ids ...string) { + if m.credit_allocations == nil { + m.credit_allocations = make(map[string]struct{}) + } + for i := range ids { + m.credit_allocations[ids[i]] = struct{}{} + } +} + +// ClearCreditAllocations clears the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (m *ChargeUsageBasedRunsMutation) ClearCreditAllocations() { + m.clearedcredit_allocations = true +} + +// CreditAllocationsCleared reports if the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity was cleared. +func (m *ChargeUsageBasedRunsMutation) CreditAllocationsCleared() bool { + return m.clearedcredit_allocations +} + +// RemoveCreditAllocationIDs removes the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity by IDs. +func (m *ChargeUsageBasedRunsMutation) RemoveCreditAllocationIDs(ids ...string) { + if m.removedcredit_allocations == nil { + m.removedcredit_allocations = make(map[string]struct{}) + } + for i := range ids { + delete(m.credit_allocations, ids[i]) + m.removedcredit_allocations[ids[i]] = struct{}{} + } +} + +// RemovedCreditAllocations returns the removed IDs of the "credit_allocations" edge to the ChargeUsageBasedRunCreditAllocations entity. +func (m *ChargeUsageBasedRunsMutation) RemovedCreditAllocationsIDs() (ids []string) { + for id := range m.removedcredit_allocations { + ids = append(ids, id) + } + return +} + +// CreditAllocationsIDs returns the "credit_allocations" edge IDs in the mutation. +func (m *ChargeUsageBasedRunsMutation) CreditAllocationsIDs() (ids []string) { + for id := range m.credit_allocations { + ids = append(ids, id) + } + return +} + +// ResetCreditAllocations resets all changes to the "credit_allocations" edge. +func (m *ChargeUsageBasedRunsMutation) ResetCreditAllocations() { + m.credit_allocations = nil + m.clearedcredit_allocations = false + m.removedcredit_allocations = nil +} + +// SetInvoicedUsageID sets the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity by id. +func (m *ChargeUsageBasedRunsMutation) SetInvoicedUsageID(id string) { + m.invoiced_usage = &id +} + +// ClearInvoicedUsage clears the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity. +func (m *ChargeUsageBasedRunsMutation) ClearInvoicedUsage() { + m.clearedinvoiced_usage = true +} + +// InvoicedUsageCleared reports if the "invoiced_usage" edge to the ChargeUsageBasedRunInvoicedUsage entity was cleared. +func (m *ChargeUsageBasedRunsMutation) InvoicedUsageCleared() bool { + return m.clearedinvoiced_usage +} + +// InvoicedUsageID returns the "invoiced_usage" edge ID in the mutation. +func (m *ChargeUsageBasedRunsMutation) InvoicedUsageID() (id string, exists bool) { + if m.invoiced_usage != nil { + return *m.invoiced_usage, true + } + return +} + +// InvoicedUsageIDs returns the "invoiced_usage" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InvoicedUsageID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunsMutation) InvoicedUsageIDs() (ids []string) { + if id := m.invoiced_usage; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInvoicedUsage resets all changes to the "invoiced_usage" edge. +func (m *ChargeUsageBasedRunsMutation) ResetInvoicedUsage() { + m.invoiced_usage = nil + m.clearedinvoiced_usage = false +} + +// SetPaymentID sets the "payment" edge to the ChargeUsageBasedRunPayment entity by id. +func (m *ChargeUsageBasedRunsMutation) SetPaymentID(id string) { + m.payment = &id +} + +// ClearPayment clears the "payment" edge to the ChargeUsageBasedRunPayment entity. +func (m *ChargeUsageBasedRunsMutation) ClearPayment() { + m.clearedpayment = true +} + +// PaymentCleared reports if the "payment" edge to the ChargeUsageBasedRunPayment entity was cleared. +func (m *ChargeUsageBasedRunsMutation) PaymentCleared() bool { + return m.clearedpayment +} + +// PaymentID returns the "payment" edge ID in the mutation. +func (m *ChargeUsageBasedRunsMutation) PaymentID() (id string, exists bool) { + if m.payment != nil { + return *m.payment, true + } + return +} + +// PaymentIDs returns the "payment" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PaymentID instead. It exists only for internal usage by the builders. +func (m *ChargeUsageBasedRunsMutation) PaymentIDs() (ids []string) { + if id := m.payment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPayment resets all changes to the "payment" edge. +func (m *ChargeUsageBasedRunsMutation) ResetPayment() { + m.payment = nil + m.clearedpayment = false +} + +// Where appends a list predicates to the ChargeUsageBasedRunsMutation builder. +func (m *ChargeUsageBasedRunsMutation) Where(ps ...predicate.ChargeUsageBasedRuns) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ChargeUsageBasedRunsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ChargeUsageBasedRunsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ChargeUsageBasedRuns, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ChargeUsageBasedRunsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ChargeUsageBasedRunsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ChargeUsageBasedRuns). +func (m *ChargeUsageBasedRunsMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ChargeUsageBasedRunsMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.namespace != nil { + fields = append(fields, chargeusagebasedruns.FieldNamespace) + } + if m.created_at != nil { + fields = append(fields, chargeusagebasedruns.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, chargeusagebasedruns.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, chargeusagebasedruns.FieldDeletedAt) + } + if m.usage_based != nil { + fields = append(fields, chargeusagebasedruns.FieldChargeID) + } + if m._type != nil { + fields = append(fields, chargeusagebasedruns.FieldType) + } + if m.asof != nil { + fields = append(fields, chargeusagebasedruns.FieldAsof) + } + if m.meter_value != nil { + fields = append(fields, chargeusagebasedruns.FieldMeterValue) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ChargeUsageBasedRunsMutation) Field(name string) (ent.Value, bool) { + switch name { + case chargeusagebasedruns.FieldNamespace: + return m.Namespace() + case chargeusagebasedruns.FieldCreatedAt: + return m.CreatedAt() + case chargeusagebasedruns.FieldUpdatedAt: + return m.UpdatedAt() + case chargeusagebasedruns.FieldDeletedAt: + return m.DeletedAt() + case chargeusagebasedruns.FieldChargeID: + return m.ChargeID() + case chargeusagebasedruns.FieldType: + return m.GetType() + case chargeusagebasedruns.FieldAsof: + return m.Asof() + case chargeusagebasedruns.FieldMeterValue: + return m.MeterValue() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ChargeUsageBasedRunsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case chargeusagebasedruns.FieldNamespace: + return m.OldNamespace(ctx) + case chargeusagebasedruns.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case chargeusagebasedruns.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case chargeusagebasedruns.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case chargeusagebasedruns.FieldChargeID: + return m.OldChargeID(ctx) + case chargeusagebasedruns.FieldType: + return m.OldType(ctx) + case chargeusagebasedruns.FieldAsof: + return m.OldAsof(ctx) + case chargeusagebasedruns.FieldMeterValue: + return m.OldMeterValue(ctx) + } + return nil, fmt.Errorf("unknown ChargeUsageBasedRuns field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunsMutation) SetField(name string, value ent.Value) error { + switch name { + case chargeusagebasedruns.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case chargeusagebasedruns.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case chargeusagebasedruns.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case chargeusagebasedruns.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case chargeusagebasedruns.FieldChargeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChargeID(v) + return nil + case chargeusagebasedruns.FieldType: + v, ok := value.(usagebased.RealizationRunType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case chargeusagebasedruns.FieldAsof: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAsof(v) + return nil + case chargeusagebasedruns.FieldMeterValue: + v, ok := value.(alpacadecimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMeterValue(v) + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRuns field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ChargeUsageBasedRunsMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ChargeUsageBasedRunsMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ChargeUsageBasedRunsMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ChargeUsageBasedRuns numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ChargeUsageBasedRunsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(chargeusagebasedruns.FieldDeletedAt) { + fields = append(fields, chargeusagebasedruns.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ChargeUsageBasedRunsMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunsMutation) ClearField(name string) error { + switch name { + case chargeusagebasedruns.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRuns nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ChargeUsageBasedRunsMutation) ResetField(name string) error { + switch name { + case chargeusagebasedruns.FieldNamespace: + m.ResetNamespace() + return nil + case chargeusagebasedruns.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case chargeusagebasedruns.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case chargeusagebasedruns.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case chargeusagebasedruns.FieldChargeID: + m.ResetChargeID() + return nil + case chargeusagebasedruns.FieldType: + m.ResetType() + return nil + case chargeusagebasedruns.FieldAsof: + m.ResetAsof() + return nil + case chargeusagebasedruns.FieldMeterValue: + m.ResetMeterValue() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRuns field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ChargeUsageBasedRunsMutation) AddedEdges() []string { + edges := make([]string, 0, 4) + if m.usage_based != nil { + edges = append(edges, chargeusagebasedruns.EdgeUsageBased) + } + if m.credit_allocations != nil { + edges = append(edges, chargeusagebasedruns.EdgeCreditAllocations) + } + if m.invoiced_usage != nil { + edges = append(edges, chargeusagebasedruns.EdgeInvoicedUsage) + } + if m.payment != nil { + edges = append(edges, chargeusagebasedruns.EdgePayment) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ChargeUsageBasedRunsMutation) AddedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedruns.EdgeUsageBased: + if id := m.usage_based; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedruns.EdgeCreditAllocations: + ids := make([]ent.Value, 0, len(m.credit_allocations)) + for id := range m.credit_allocations { + ids = append(ids, id) + } + return ids + case chargeusagebasedruns.EdgeInvoicedUsage: + if id := m.invoiced_usage; id != nil { + return []ent.Value{*id} + } + case chargeusagebasedruns.EdgePayment: + if id := m.payment; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ChargeUsageBasedRunsMutation) RemovedEdges() []string { + edges := make([]string, 0, 4) + if m.removedcredit_allocations != nil { + edges = append(edges, chargeusagebasedruns.EdgeCreditAllocations) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ChargeUsageBasedRunsMutation) RemovedIDs(name string) []ent.Value { + switch name { + case chargeusagebasedruns.EdgeCreditAllocations: + ids := make([]ent.Value, 0, len(m.removedcredit_allocations)) + for id := range m.removedcredit_allocations { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ChargeUsageBasedRunsMutation) ClearedEdges() []string { + edges := make([]string, 0, 4) + if m.clearedusage_based { + edges = append(edges, chargeusagebasedruns.EdgeUsageBased) + } + if m.clearedcredit_allocations { + edges = append(edges, chargeusagebasedruns.EdgeCreditAllocations) + } + if m.clearedinvoiced_usage { + edges = append(edges, chargeusagebasedruns.EdgeInvoicedUsage) + } + if m.clearedpayment { + edges = append(edges, chargeusagebasedruns.EdgePayment) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ChargeUsageBasedRunsMutation) EdgeCleared(name string) bool { + switch name { + case chargeusagebasedruns.EdgeUsageBased: + return m.clearedusage_based + case chargeusagebasedruns.EdgeCreditAllocations: + return m.clearedcredit_allocations + case chargeusagebasedruns.EdgeInvoicedUsage: + return m.clearedinvoiced_usage + case chargeusagebasedruns.EdgePayment: + return m.clearedpayment + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ChargeUsageBasedRunsMutation) ClearEdge(name string) error { + switch name { + case chargeusagebasedruns.EdgeUsageBased: + m.ClearUsageBased() + return nil + case chargeusagebasedruns.EdgeInvoicedUsage: + m.ClearInvoicedUsage() + return nil + case chargeusagebasedruns.EdgePayment: + m.ClearPayment() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRuns unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ChargeUsageBasedRunsMutation) ResetEdge(name string) error { + switch name { + case chargeusagebasedruns.EdgeUsageBased: + m.ResetUsageBased() + return nil + case chargeusagebasedruns.EdgeCreditAllocations: + m.ResetCreditAllocations() + return nil + case chargeusagebasedruns.EdgeInvoicedUsage: + m.ResetInvoicedUsage() + return nil + case chargeusagebasedruns.EdgePayment: + m.ResetPayment() + return nil + } + return fmt.Errorf("unknown ChargeUsageBasedRuns edge %s", name) +} + // CurrencyCostBasisMutation represents an operation that mutates the CurrencyCostBasis nodes in the graph. type CurrencyCostBasisMutation struct { config diff --git a/openmeter/ent/db/paginate.go b/openmeter/ent/db/paginate.go index 47aa27f3e6..c8284120cc 100644 --- a/openmeter/ent/db/paginate.go +++ b/openmeter/ent/db/paginate.go @@ -1865,6 +1865,296 @@ func (_m *ChargeFlatFeePaymentQuery) Paginate(ctx context.Context, page paginati // type check var _ pagination.Paginator[*ChargeFlatFeePayment] = (*ChargeFlatFeePaymentQuery)(nil) +// Paginate runs the query and returns a paginated response. +// If page is its 0 value then it will return all the items and populate the response page accordingly. +func (_m *ChargeUsageBasedQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBased], error) { + // Get the limit and offset + limit, offset := page.Limit(), page.Offset() + + // Unset previous pagination settings + zero := 0 + _m.ctx.Offset = &zero + _m.ctx.Limit = &zero + + // Create duplicate of the query to run for + countQuery := _m.Clone() + pagedQuery := _m + + // Unset select for count query + countQuery.ctx.Fields = []string{} + + // Unset ordering for count query + countQuery.order = nil + + pagedResponse := pagination.Result[*ChargeUsageBased]{ + Page: page, + } + + // Get the total count + count, err := countQuery.Count(ctx) + if err != nil { + return pagedResponse, fmt.Errorf("failed to get count: %w", err) + } + pagedResponse.TotalCount = count + + // If there are no items, return the empty response early + if count == 0 { + // Items should be [] not null. + pagedResponse.Items = make([]*ChargeUsageBased, 0) + return pagedResponse, nil + } + + // If page is its 0 value then return all the items + if page.IsZero() { + offset = 0 + limit = count + } + + // Set the limit and offset + pagedQuery.ctx.Limit = &limit + pagedQuery.ctx.Offset = &offset + + // Get the paged items + items, err := pagedQuery.All(ctx) + pagedResponse.Items = items + return pagedResponse, err +} + +// type check +var _ pagination.Paginator[*ChargeUsageBased] = (*ChargeUsageBasedQuery)(nil) + +// Paginate runs the query and returns a paginated response. +// If page is its 0 value then it will return all the items and populate the response page accordingly. +func (_m *ChargeUsageBasedRunCreditAllocationsQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBasedRunCreditAllocations], error) { + // Get the limit and offset + limit, offset := page.Limit(), page.Offset() + + // Unset previous pagination settings + zero := 0 + _m.ctx.Offset = &zero + _m.ctx.Limit = &zero + + // Create duplicate of the query to run for + countQuery := _m.Clone() + pagedQuery := _m + + // Unset select for count query + countQuery.ctx.Fields = []string{} + + // Unset ordering for count query + countQuery.order = nil + + pagedResponse := pagination.Result[*ChargeUsageBasedRunCreditAllocations]{ + Page: page, + } + + // Get the total count + count, err := countQuery.Count(ctx) + if err != nil { + return pagedResponse, fmt.Errorf("failed to get count: %w", err) + } + pagedResponse.TotalCount = count + + // If there are no items, return the empty response early + if count == 0 { + // Items should be [] not null. + pagedResponse.Items = make([]*ChargeUsageBasedRunCreditAllocations, 0) + return pagedResponse, nil + } + + // If page is its 0 value then return all the items + if page.IsZero() { + offset = 0 + limit = count + } + + // Set the limit and offset + pagedQuery.ctx.Limit = &limit + pagedQuery.ctx.Offset = &offset + + // Get the paged items + items, err := pagedQuery.All(ctx) + pagedResponse.Items = items + return pagedResponse, err +} + +// type check +var _ pagination.Paginator[*ChargeUsageBasedRunCreditAllocations] = (*ChargeUsageBasedRunCreditAllocationsQuery)(nil) + +// Paginate runs the query and returns a paginated response. +// If page is its 0 value then it will return all the items and populate the response page accordingly. +func (_m *ChargeUsageBasedRunInvoicedUsageQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBasedRunInvoicedUsage], error) { + // Get the limit and offset + limit, offset := page.Limit(), page.Offset() + + // Unset previous pagination settings + zero := 0 + _m.ctx.Offset = &zero + _m.ctx.Limit = &zero + + // Create duplicate of the query to run for + countQuery := _m.Clone() + pagedQuery := _m + + // Unset select for count query + countQuery.ctx.Fields = []string{} + + // Unset ordering for count query + countQuery.order = nil + + pagedResponse := pagination.Result[*ChargeUsageBasedRunInvoicedUsage]{ + Page: page, + } + + // Get the total count + count, err := countQuery.Count(ctx) + if err != nil { + return pagedResponse, fmt.Errorf("failed to get count: %w", err) + } + pagedResponse.TotalCount = count + + // If there are no items, return the empty response early + if count == 0 { + // Items should be [] not null. + pagedResponse.Items = make([]*ChargeUsageBasedRunInvoicedUsage, 0) + return pagedResponse, nil + } + + // If page is its 0 value then return all the items + if page.IsZero() { + offset = 0 + limit = count + } + + // Set the limit and offset + pagedQuery.ctx.Limit = &limit + pagedQuery.ctx.Offset = &offset + + // Get the paged items + items, err := pagedQuery.All(ctx) + pagedResponse.Items = items + return pagedResponse, err +} + +// type check +var _ pagination.Paginator[*ChargeUsageBasedRunInvoicedUsage] = (*ChargeUsageBasedRunInvoicedUsageQuery)(nil) + +// Paginate runs the query and returns a paginated response. +// If page is its 0 value then it will return all the items and populate the response page accordingly. +func (_m *ChargeUsageBasedRunPaymentQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBasedRunPayment], error) { + // Get the limit and offset + limit, offset := page.Limit(), page.Offset() + + // Unset previous pagination settings + zero := 0 + _m.ctx.Offset = &zero + _m.ctx.Limit = &zero + + // Create duplicate of the query to run for + countQuery := _m.Clone() + pagedQuery := _m + + // Unset select for count query + countQuery.ctx.Fields = []string{} + + // Unset ordering for count query + countQuery.order = nil + + pagedResponse := pagination.Result[*ChargeUsageBasedRunPayment]{ + Page: page, + } + + // Get the total count + count, err := countQuery.Count(ctx) + if err != nil { + return pagedResponse, fmt.Errorf("failed to get count: %w", err) + } + pagedResponse.TotalCount = count + + // If there are no items, return the empty response early + if count == 0 { + // Items should be [] not null. + pagedResponse.Items = make([]*ChargeUsageBasedRunPayment, 0) + return pagedResponse, nil + } + + // If page is its 0 value then return all the items + if page.IsZero() { + offset = 0 + limit = count + } + + // Set the limit and offset + pagedQuery.ctx.Limit = &limit + pagedQuery.ctx.Offset = &offset + + // Get the paged items + items, err := pagedQuery.All(ctx) + pagedResponse.Items = items + return pagedResponse, err +} + +// type check +var _ pagination.Paginator[*ChargeUsageBasedRunPayment] = (*ChargeUsageBasedRunPaymentQuery)(nil) + +// Paginate runs the query and returns a paginated response. +// If page is its 0 value then it will return all the items and populate the response page accordingly. +func (_m *ChargeUsageBasedRunsQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*ChargeUsageBasedRuns], error) { + // Get the limit and offset + limit, offset := page.Limit(), page.Offset() + + // Unset previous pagination settings + zero := 0 + _m.ctx.Offset = &zero + _m.ctx.Limit = &zero + + // Create duplicate of the query to run for + countQuery := _m.Clone() + pagedQuery := _m + + // Unset select for count query + countQuery.ctx.Fields = []string{} + + // Unset ordering for count query + countQuery.order = nil + + pagedResponse := pagination.Result[*ChargeUsageBasedRuns]{ + Page: page, + } + + // Get the total count + count, err := countQuery.Count(ctx) + if err != nil { + return pagedResponse, fmt.Errorf("failed to get count: %w", err) + } + pagedResponse.TotalCount = count + + // If there are no items, return the empty response early + if count == 0 { + // Items should be [] not null. + pagedResponse.Items = make([]*ChargeUsageBasedRuns, 0) + return pagedResponse, nil + } + + // If page is its 0 value then return all the items + if page.IsZero() { + offset = 0 + limit = count + } + + // Set the limit and offset + pagedQuery.ctx.Limit = &limit + pagedQuery.ctx.Offset = &offset + + // Get the paged items + items, err := pagedQuery.All(ctx) + pagedResponse.Items = items + return pagedResponse, err +} + +// type check +var _ pagination.Paginator[*ChargeUsageBasedRuns] = (*ChargeUsageBasedRunsQuery)(nil) + // Paginate runs the query and returns a paginated response. // If page is its 0 value then it will return all the items and populate the response page accordingly. func (_m *CurrencyCostBasisQuery) Paginate(ctx context.Context, page pagination.Page) (pagination.Result[*CurrencyCostBasis], error) { diff --git a/openmeter/ent/db/predicate/predicate.go b/openmeter/ent/db/predicate/predicate.go index 02c13b08f5..c7852e0c11 100644 --- a/openmeter/ent/db/predicate/predicate.go +++ b/openmeter/ent/db/predicate/predicate.go @@ -223,6 +223,32 @@ type ChargeFlatFeeInvoicedUsage func(*sql.Selector) // ChargeFlatFeePayment is the predicate function for chargeflatfeepayment builders. type ChargeFlatFeePayment func(*sql.Selector) +// ChargeUsageBased is the predicate function for chargeusagebased builders. +type ChargeUsageBased func(*sql.Selector) + +// ChargeUsageBasedOrErr calls the predicate only if the error is not nit. +func ChargeUsageBasedOrErr(p ChargeUsageBased, err error) ChargeUsageBased { + return func(s *sql.Selector) { + if err != nil { + s.AddError(err) + return + } + p(s) + } +} + +// ChargeUsageBasedRunCreditAllocations is the predicate function for chargeusagebasedruncreditallocations builders. +type ChargeUsageBasedRunCreditAllocations func(*sql.Selector) + +// ChargeUsageBasedRunInvoicedUsage is the predicate function for chargeusagebasedruninvoicedusage builders. +type ChargeUsageBasedRunInvoicedUsage func(*sql.Selector) + +// ChargeUsageBasedRunPayment is the predicate function for chargeusagebasedrunpayment builders. +type ChargeUsageBasedRunPayment func(*sql.Selector) + +// ChargeUsageBasedRuns is the predicate function for chargeusagebasedruns builders. +type ChargeUsageBasedRuns func(*sql.Selector) + // CurrencyCostBasis is the predicate function for currencycostbasis builders. type CurrencyCostBasis func(*sql.Selector) diff --git a/openmeter/ent/db/runtime.go b/openmeter/ent/db/runtime.go index a2ec698119..dc13bdc754 100644 --- a/openmeter/ent/db/runtime.go +++ b/openmeter/ent/db/runtime.go @@ -40,6 +40,11 @@ import ( "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeecreditallocations" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeeinvoicedusage" "github.com/openmeterio/openmeter/openmeter/ent/db/chargeflatfeepayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebased" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruncreditallocations" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruninvoicedusage" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedrunpayment" + "github.com/openmeterio/openmeter/openmeter/ent/db/chargeusagebasedruns" "github.com/openmeterio/openmeter/openmeter/ent/db/currencycostbasis" "github.com/openmeterio/openmeter/openmeter/ent/db/customcurrency" "github.com/openmeterio/openmeter/openmeter/ent/db/customer" @@ -557,7 +562,7 @@ func init() { billinginvoicelineDescRatecardDiscounts := billinginvoicelineFields[9].Descriptor() billinginvoiceline.ValueScanner.RatecardDiscounts = billinginvoicelineDescRatecardDiscounts.ValueScanner.(field.TypeValueScanner[*billing.Discounts]) // billinginvoicelineDescCreditsApplied is the schema descriptor for credits_applied field. - billinginvoicelineDescCreditsApplied := billinginvoicelineFields[20].Descriptor() + billinginvoicelineDescCreditsApplied := billinginvoicelineFields[21].Descriptor() billinginvoiceline.ValueScanner.CreditsApplied = billinginvoicelineDescCreditsApplied.ValueScanner.(field.TypeValueScanner[*billing.CreditsApplied]) // billinginvoicelineDescID is the schema descriptor for id field. billinginvoicelineDescID := billinginvoicelineMixinFields1[0].Descriptor() @@ -1099,6 +1104,151 @@ func init() { chargeflatfeepaymentDescID := chargeflatfeepaymentMixinFields0[10].Descriptor() // chargeflatfeepayment.DefaultID holds the default value on creation for the id field. chargeflatfeepayment.DefaultID = chargeflatfeepaymentDescID.Default.(func() string) + chargeusagebasedMixin := schema.ChargeUsageBased{}.Mixin() + chargeusagebasedMixinFields0 := chargeusagebasedMixin[0].Fields() + _ = chargeusagebasedMixinFields0 + chargeusagebasedMixinFields1 := chargeusagebasedMixin[1].Fields() + _ = chargeusagebasedMixinFields1 + chargeusagebasedFields := schema.ChargeUsageBased{}.Fields() + _ = chargeusagebasedFields + // chargeusagebasedDescNamespace is the schema descriptor for namespace field. + chargeusagebasedDescNamespace := chargeusagebasedMixinFields0[0].Descriptor() + // chargeusagebased.NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + chargeusagebased.NamespaceValidator = chargeusagebasedDescNamespace.Validators[0].(func(string) error) + // chargeusagebasedDescDiscounts is the schema descriptor for discounts field. + chargeusagebasedDescDiscounts := chargeusagebasedFields[2].Descriptor() + chargeusagebased.ValueScanner.Discounts = chargeusagebasedDescDiscounts.ValueScanner.(field.TypeValueScanner[*productcatalog.Discounts]) + // chargeusagebasedDescFeatureKey is the schema descriptor for feature_key field. + chargeusagebasedDescFeatureKey := chargeusagebasedFields[3].Descriptor() + // chargeusagebased.FeatureKeyValidator is a validator for the "feature_key" field. It is called by the builders before save. + chargeusagebased.FeatureKeyValidator = chargeusagebasedDescFeatureKey.Validators[0].(func(string) error) + // chargeusagebasedDescPrice is the schema descriptor for price field. + chargeusagebasedDescPrice := chargeusagebasedFields[4].Descriptor() + chargeusagebased.ValueScanner.Price = chargeusagebasedDescPrice.ValueScanner.(field.TypeValueScanner[*productcatalog.Price]) + // chargeusagebasedDescID is the schema descriptor for id field. + chargeusagebasedDescID := chargeusagebasedMixinFields1[0].Descriptor() + // chargeusagebased.DefaultID holds the default value on creation for the id field. + chargeusagebased.DefaultID = chargeusagebasedDescID.Default.(func() string) + chargeusagebasedruncreditallocationsMixin := schema.ChargeUsageBasedRunCreditAllocations{}.Mixin() + chargeusagebasedruncreditallocationsMixinFields0 := chargeusagebasedruncreditallocationsMixin[0].Fields() + _ = chargeusagebasedruncreditallocationsMixinFields0 + chargeusagebasedruncreditallocationsFields := schema.ChargeUsageBasedRunCreditAllocations{}.Fields() + _ = chargeusagebasedruncreditallocationsFields + // chargeusagebasedruncreditallocationsDescLineID is the schema descriptor for line_id field. + chargeusagebasedruncreditallocationsDescLineID := chargeusagebasedruncreditallocationsMixinFields0[0].Descriptor() + // chargeusagebasedruncreditallocations.LineIDValidator is a validator for the "line_id" field. It is called by the builders before save. + chargeusagebasedruncreditallocations.LineIDValidator = chargeusagebasedruncreditallocationsDescLineID.Validators[0].(func(string) error) + // chargeusagebasedruncreditallocationsDescLedgerTransactionGroupID is the schema descriptor for ledger_transaction_group_id field. + chargeusagebasedruncreditallocationsDescLedgerTransactionGroupID := chargeusagebasedruncreditallocationsMixinFields0[4].Descriptor() + // chargeusagebasedruncreditallocations.LedgerTransactionGroupIDValidator is a validator for the "ledger_transaction_group_id" field. It is called by the builders before save. + chargeusagebasedruncreditallocations.LedgerTransactionGroupIDValidator = chargeusagebasedruncreditallocationsDescLedgerTransactionGroupID.Validators[0].(func(string) error) + // chargeusagebasedruncreditallocationsDescNamespace is the schema descriptor for namespace field. + chargeusagebasedruncreditallocationsDescNamespace := chargeusagebasedruncreditallocationsMixinFields0[5].Descriptor() + // chargeusagebasedruncreditallocations.NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + chargeusagebasedruncreditallocations.NamespaceValidator = chargeusagebasedruncreditallocationsDescNamespace.Validators[0].(func(string) error) + // chargeusagebasedruncreditallocationsDescCreatedAt is the schema descriptor for created_at field. + chargeusagebasedruncreditallocationsDescCreatedAt := chargeusagebasedruncreditallocationsMixinFields0[7].Descriptor() + // chargeusagebasedruncreditallocations.DefaultCreatedAt holds the default value on creation for the created_at field. + chargeusagebasedruncreditallocations.DefaultCreatedAt = chargeusagebasedruncreditallocationsDescCreatedAt.Default.(func() time.Time) + // chargeusagebasedruncreditallocationsDescUpdatedAt is the schema descriptor for updated_at field. + chargeusagebasedruncreditallocationsDescUpdatedAt := chargeusagebasedruncreditallocationsMixinFields0[8].Descriptor() + // chargeusagebasedruncreditallocations.DefaultUpdatedAt holds the default value on creation for the updated_at field. + chargeusagebasedruncreditallocations.DefaultUpdatedAt = chargeusagebasedruncreditallocationsDescUpdatedAt.Default.(func() time.Time) + // chargeusagebasedruncreditallocations.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + chargeusagebasedruncreditallocations.UpdateDefaultUpdatedAt = chargeusagebasedruncreditallocationsDescUpdatedAt.UpdateDefault.(func() time.Time) + // chargeusagebasedruncreditallocationsDescID is the schema descriptor for id field. + chargeusagebasedruncreditallocationsDescID := chargeusagebasedruncreditallocationsMixinFields0[6].Descriptor() + // chargeusagebasedruncreditallocations.DefaultID holds the default value on creation for the id field. + chargeusagebasedruncreditallocations.DefaultID = chargeusagebasedruncreditallocationsDescID.Default.(func() string) + chargeusagebasedruninvoicedusageMixin := schema.ChargeUsageBasedRunInvoicedUsage{}.Mixin() + chargeusagebasedruninvoicedusageMixinFields0 := chargeusagebasedruninvoicedusageMixin[0].Fields() + _ = chargeusagebasedruninvoicedusageMixinFields0 + chargeusagebasedruninvoicedusageFields := schema.ChargeUsageBasedRunInvoicedUsage{}.Fields() + _ = chargeusagebasedruninvoicedusageFields + // chargeusagebasedruninvoicedusageDescLineID is the schema descriptor for line_id field. + chargeusagebasedruninvoicedusageDescLineID := chargeusagebasedruninvoicedusageMixinFields0[0].Descriptor() + // chargeusagebasedruninvoicedusage.LineIDValidator is a validator for the "line_id" field. It is called by the builders before save. + chargeusagebasedruninvoicedusage.LineIDValidator = chargeusagebasedruninvoicedusageDescLineID.Validators[0].(func(string) error) + // chargeusagebasedruninvoicedusageDescLedgerTransactionGroupID is the schema descriptor for ledger_transaction_group_id field. + chargeusagebasedruninvoicedusageDescLedgerTransactionGroupID := chargeusagebasedruninvoicedusageMixinFields0[4].Descriptor() + // chargeusagebasedruninvoicedusage.LedgerTransactionGroupIDValidator is a validator for the "ledger_transaction_group_id" field. It is called by the builders before save. + chargeusagebasedruninvoicedusage.LedgerTransactionGroupIDValidator = chargeusagebasedruninvoicedusageDescLedgerTransactionGroupID.Validators[0].(func(string) error) + // chargeusagebasedruninvoicedusageDescNamespace is the schema descriptor for namespace field. + chargeusagebasedruninvoicedusageDescNamespace := chargeusagebasedruninvoicedusageMixinFields0[5].Descriptor() + // chargeusagebasedruninvoicedusage.NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + chargeusagebasedruninvoicedusage.NamespaceValidator = chargeusagebasedruninvoicedusageDescNamespace.Validators[0].(func(string) error) + // chargeusagebasedruninvoicedusageDescCreatedAt is the schema descriptor for created_at field. + chargeusagebasedruninvoicedusageDescCreatedAt := chargeusagebasedruninvoicedusageMixinFields0[7].Descriptor() + // chargeusagebasedruninvoicedusage.DefaultCreatedAt holds the default value on creation for the created_at field. + chargeusagebasedruninvoicedusage.DefaultCreatedAt = chargeusagebasedruninvoicedusageDescCreatedAt.Default.(func() time.Time) + // chargeusagebasedruninvoicedusageDescUpdatedAt is the schema descriptor for updated_at field. + chargeusagebasedruninvoicedusageDescUpdatedAt := chargeusagebasedruninvoicedusageMixinFields0[8].Descriptor() + // chargeusagebasedruninvoicedusage.DefaultUpdatedAt holds the default value on creation for the updated_at field. + chargeusagebasedruninvoicedusage.DefaultUpdatedAt = chargeusagebasedruninvoicedusageDescUpdatedAt.Default.(func() time.Time) + // chargeusagebasedruninvoicedusage.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + chargeusagebasedruninvoicedusage.UpdateDefaultUpdatedAt = chargeusagebasedruninvoicedusageDescUpdatedAt.UpdateDefault.(func() time.Time) + // chargeusagebasedruninvoicedusageDescID is the schema descriptor for id field. + chargeusagebasedruninvoicedusageDescID := chargeusagebasedruninvoicedusageMixinFields0[6].Descriptor() + // chargeusagebasedruninvoicedusage.DefaultID holds the default value on creation for the id field. + chargeusagebasedruninvoicedusage.DefaultID = chargeusagebasedruninvoicedusageDescID.Default.(func() string) + chargeusagebasedrunpaymentMixin := schema.ChargeUsageBasedRunPayment{}.Mixin() + chargeusagebasedrunpaymentMixinFields0 := chargeusagebasedrunpaymentMixin[0].Fields() + _ = chargeusagebasedrunpaymentMixinFields0 + chargeusagebasedrunpaymentFields := schema.ChargeUsageBasedRunPayment{}.Fields() + _ = chargeusagebasedrunpaymentFields + // chargeusagebasedrunpaymentDescAuthorizedTransactionGroupID is the schema descriptor for authorized_transaction_group_id field. + chargeusagebasedrunpaymentDescAuthorizedTransactionGroupID := chargeusagebasedrunpaymentMixinFields0[5].Descriptor() + // chargeusagebasedrunpayment.AuthorizedTransactionGroupIDValidator is a validator for the "authorized_transaction_group_id" field. It is called by the builders before save. + chargeusagebasedrunpayment.AuthorizedTransactionGroupIDValidator = chargeusagebasedrunpaymentDescAuthorizedTransactionGroupID.Validators[0].(func(string) error) + // chargeusagebasedrunpaymentDescSettledTransactionGroupID is the schema descriptor for settled_transaction_group_id field. + chargeusagebasedrunpaymentDescSettledTransactionGroupID := chargeusagebasedrunpaymentMixinFields0[7].Descriptor() + // chargeusagebasedrunpayment.SettledTransactionGroupIDValidator is a validator for the "settled_transaction_group_id" field. It is called by the builders before save. + chargeusagebasedrunpayment.SettledTransactionGroupIDValidator = chargeusagebasedrunpaymentDescSettledTransactionGroupID.Validators[0].(func(string) error) + // chargeusagebasedrunpaymentDescNamespace is the schema descriptor for namespace field. + chargeusagebasedrunpaymentDescNamespace := chargeusagebasedrunpaymentMixinFields0[9].Descriptor() + // chargeusagebasedrunpayment.NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + chargeusagebasedrunpayment.NamespaceValidator = chargeusagebasedrunpaymentDescNamespace.Validators[0].(func(string) error) + // chargeusagebasedrunpaymentDescCreatedAt is the schema descriptor for created_at field. + chargeusagebasedrunpaymentDescCreatedAt := chargeusagebasedrunpaymentMixinFields0[11].Descriptor() + // chargeusagebasedrunpayment.DefaultCreatedAt holds the default value on creation for the created_at field. + chargeusagebasedrunpayment.DefaultCreatedAt = chargeusagebasedrunpaymentDescCreatedAt.Default.(func() time.Time) + // chargeusagebasedrunpaymentDescUpdatedAt is the schema descriptor for updated_at field. + chargeusagebasedrunpaymentDescUpdatedAt := chargeusagebasedrunpaymentMixinFields0[12].Descriptor() + // chargeusagebasedrunpayment.DefaultUpdatedAt holds the default value on creation for the updated_at field. + chargeusagebasedrunpayment.DefaultUpdatedAt = chargeusagebasedrunpaymentDescUpdatedAt.Default.(func() time.Time) + // chargeusagebasedrunpayment.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + chargeusagebasedrunpayment.UpdateDefaultUpdatedAt = chargeusagebasedrunpaymentDescUpdatedAt.UpdateDefault.(func() time.Time) + // chargeusagebasedrunpaymentDescID is the schema descriptor for id field. + chargeusagebasedrunpaymentDescID := chargeusagebasedrunpaymentMixinFields0[10].Descriptor() + // chargeusagebasedrunpayment.DefaultID holds the default value on creation for the id field. + chargeusagebasedrunpayment.DefaultID = chargeusagebasedrunpaymentDescID.Default.(func() string) + chargeusagebasedrunsMixin := schema.ChargeUsageBasedRuns{}.Mixin() + chargeusagebasedrunsMixinFields0 := chargeusagebasedrunsMixin[0].Fields() + _ = chargeusagebasedrunsMixinFields0 + chargeusagebasedrunsMixinFields1 := chargeusagebasedrunsMixin[1].Fields() + _ = chargeusagebasedrunsMixinFields1 + chargeusagebasedrunsMixinFields2 := chargeusagebasedrunsMixin[2].Fields() + _ = chargeusagebasedrunsMixinFields2 + chargeusagebasedrunsFields := schema.ChargeUsageBasedRuns{}.Fields() + _ = chargeusagebasedrunsFields + // chargeusagebasedrunsDescNamespace is the schema descriptor for namespace field. + chargeusagebasedrunsDescNamespace := chargeusagebasedrunsMixinFields0[0].Descriptor() + // chargeusagebasedruns.NamespaceValidator is a validator for the "namespace" field. It is called by the builders before save. + chargeusagebasedruns.NamespaceValidator = chargeusagebasedrunsDescNamespace.Validators[0].(func(string) error) + // chargeusagebasedrunsDescCreatedAt is the schema descriptor for created_at field. + chargeusagebasedrunsDescCreatedAt := chargeusagebasedrunsMixinFields2[0].Descriptor() + // chargeusagebasedruns.DefaultCreatedAt holds the default value on creation for the created_at field. + chargeusagebasedruns.DefaultCreatedAt = chargeusagebasedrunsDescCreatedAt.Default.(func() time.Time) + // chargeusagebasedrunsDescUpdatedAt is the schema descriptor for updated_at field. + chargeusagebasedrunsDescUpdatedAt := chargeusagebasedrunsMixinFields2[1].Descriptor() + // chargeusagebasedruns.DefaultUpdatedAt holds the default value on creation for the updated_at field. + chargeusagebasedruns.DefaultUpdatedAt = chargeusagebasedrunsDescUpdatedAt.Default.(func() time.Time) + // chargeusagebasedruns.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + chargeusagebasedruns.UpdateDefaultUpdatedAt = chargeusagebasedrunsDescUpdatedAt.UpdateDefault.(func() time.Time) + // chargeusagebasedrunsDescID is the schema descriptor for id field. + chargeusagebasedrunsDescID := chargeusagebasedrunsMixinFields1[0].Descriptor() + // chargeusagebasedruns.DefaultID holds the default value on creation for the id field. + chargeusagebasedruns.DefaultID = chargeusagebasedrunsDescID.Default.(func() string) currencycostbasisMixin := schema.CurrencyCostBasis{}.Mixin() currencycostbasisMixinFields0 := currencycostbasisMixin[0].Fields() _ = currencycostbasisMixinFields0 diff --git a/openmeter/ent/db/setorclear.go b/openmeter/ent/db/setorclear.go index ff202a3417..046b87600c 100644 --- a/openmeter/ent/db/setorclear.go +++ b/openmeter/ent/db/setorclear.go @@ -2509,6 +2509,216 @@ func (u *ChargeFlatFeePaymentUpdateOne) SetOrClearAnnotations(value *models.Anno return u.SetAnnotations(*value) } +func (u *ChargeUsageBasedUpdate) SetOrClearDiscounts(value **productcatalog.Discounts) *ChargeUsageBasedUpdate { + if value == nil { + return u.ClearDiscounts() + } + return u.SetDiscounts(*value) +} + +func (u *ChargeUsageBasedUpdateOne) SetOrClearDiscounts(value **productcatalog.Discounts) *ChargeUsageBasedUpdateOne { + if value == nil { + return u.ClearDiscounts() + } + return u.SetDiscounts(*value) +} + +func (u *ChargeUsageBasedRunCreditAllocationsUpdate) SetOrClearLineID(value *string) *ChargeUsageBasedRunCreditAllocationsUpdate { + if value == nil { + return u.ClearLineID() + } + return u.SetLineID(*value) +} + +func (u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetOrClearLineID(value *string) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if value == nil { + return u.ClearLineID() + } + return u.SetLineID(*value) +} + +func (u *ChargeUsageBasedRunCreditAllocationsUpdate) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdate { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunCreditAllocationsUpdate) SetOrClearAnnotations(value *models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpdate { + if value == nil { + return u.ClearAnnotations() + } + return u.SetAnnotations(*value) +} + +func (u *ChargeUsageBasedRunCreditAllocationsUpdateOne) SetOrClearAnnotations(value *models.Annotations) *ChargeUsageBasedRunCreditAllocationsUpdateOne { + if value == nil { + return u.ClearAnnotations() + } + return u.SetAnnotations(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdate) SetOrClearLineID(value *string) *ChargeUsageBasedRunInvoicedUsageUpdate { + if value == nil { + return u.ClearLineID() + } + return u.SetLineID(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetOrClearLineID(value *string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if value == nil { + return u.ClearLineID() + } + return u.SetLineID(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdate) SetOrClearLedgerTransactionGroupID(value *string) *ChargeUsageBasedRunInvoicedUsageUpdate { + if value == nil { + return u.ClearLedgerTransactionGroupID() + } + return u.SetLedgerTransactionGroupID(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetOrClearLedgerTransactionGroupID(value *string) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if value == nil { + return u.ClearLedgerTransactionGroupID() + } + return u.SetLedgerTransactionGroupID(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdate) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdate { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdate) SetOrClearAnnotations(value *models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpdate { + if value == nil { + return u.ClearAnnotations() + } + return u.SetAnnotations(*value) +} + +func (u *ChargeUsageBasedRunInvoicedUsageUpdateOne) SetOrClearAnnotations(value *models.Annotations) *ChargeUsageBasedRunInvoicedUsageUpdateOne { + if value == nil { + return u.ClearAnnotations() + } + return u.SetAnnotations(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdate) SetOrClearAuthorizedTransactionGroupID(value *string) *ChargeUsageBasedRunPaymentUpdate { + if value == nil { + return u.ClearAuthorizedTransactionGroupID() + } + return u.SetAuthorizedTransactionGroupID(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdateOne) SetOrClearAuthorizedTransactionGroupID(value *string) *ChargeUsageBasedRunPaymentUpdateOne { + if value == nil { + return u.ClearAuthorizedTransactionGroupID() + } + return u.SetAuthorizedTransactionGroupID(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdate) SetOrClearAuthorizedAt(value *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if value == nil { + return u.ClearAuthorizedAt() + } + return u.SetAuthorizedAt(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdateOne) SetOrClearAuthorizedAt(value *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if value == nil { + return u.ClearAuthorizedAt() + } + return u.SetAuthorizedAt(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdate) SetOrClearSettledTransactionGroupID(value *string) *ChargeUsageBasedRunPaymentUpdate { + if value == nil { + return u.ClearSettledTransactionGroupID() + } + return u.SetSettledTransactionGroupID(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdateOne) SetOrClearSettledTransactionGroupID(value *string) *ChargeUsageBasedRunPaymentUpdateOne { + if value == nil { + return u.ClearSettledTransactionGroupID() + } + return u.SetSettledTransactionGroupID(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdate) SetOrClearSettledAt(value *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if value == nil { + return u.ClearSettledAt() + } + return u.SetSettledAt(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdateOne) SetOrClearSettledAt(value *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if value == nil { + return u.ClearSettledAt() + } + return u.SetSettledAt(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdate) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunPaymentUpdate { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdateOne) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunPaymentUpdateOne { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdate) SetOrClearAnnotations(value *models.Annotations) *ChargeUsageBasedRunPaymentUpdate { + if value == nil { + return u.ClearAnnotations() + } + return u.SetAnnotations(*value) +} + +func (u *ChargeUsageBasedRunPaymentUpdateOne) SetOrClearAnnotations(value *models.Annotations) *ChargeUsageBasedRunPaymentUpdateOne { + if value == nil { + return u.ClearAnnotations() + } + return u.SetAnnotations(*value) +} + +func (u *ChargeUsageBasedRunsUpdate) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunsUpdate { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + +func (u *ChargeUsageBasedRunsUpdateOne) SetOrClearDeletedAt(value *time.Time) *ChargeUsageBasedRunsUpdateOne { + if value == nil { + return u.ClearDeletedAt() + } + return u.SetDeletedAt(*value) +} + func (u *CurrencyCostBasisUpdate) SetOrClearDeletedAt(value *time.Time) *CurrencyCostBasisUpdate { if value == nil { return u.ClearDeletedAt() diff --git a/openmeter/ent/db/tx.go b/openmeter/ent/db/tx.go index 10ca8b61b2..5923cbc2fa 100644 --- a/openmeter/ent/db/tx.go +++ b/openmeter/ent/db/tx.go @@ -78,6 +78,16 @@ type Tx struct { ChargeFlatFeeInvoicedUsage *ChargeFlatFeeInvoicedUsageClient // ChargeFlatFeePayment is the client for interacting with the ChargeFlatFeePayment builders. ChargeFlatFeePayment *ChargeFlatFeePaymentClient + // ChargeUsageBased is the client for interacting with the ChargeUsageBased builders. + ChargeUsageBased *ChargeUsageBasedClient + // ChargeUsageBasedRunCreditAllocations is the client for interacting with the ChargeUsageBasedRunCreditAllocations builders. + ChargeUsageBasedRunCreditAllocations *ChargeUsageBasedRunCreditAllocationsClient + // ChargeUsageBasedRunInvoicedUsage is the client for interacting with the ChargeUsageBasedRunInvoicedUsage builders. + ChargeUsageBasedRunInvoicedUsage *ChargeUsageBasedRunInvoicedUsageClient + // ChargeUsageBasedRunPayment is the client for interacting with the ChargeUsageBasedRunPayment builders. + ChargeUsageBasedRunPayment *ChargeUsageBasedRunPaymentClient + // ChargeUsageBasedRuns is the client for interacting with the ChargeUsageBasedRuns builders. + ChargeUsageBasedRuns *ChargeUsageBasedRunsClient // CurrencyCostBasis is the client for interacting with the CurrencyCostBasis builders. CurrencyCostBasis *CurrencyCostBasisClient // CustomCurrency is the client for interacting with the CustomCurrency builders. @@ -293,6 +303,11 @@ func (tx *Tx) init() { tx.ChargeFlatFeeCreditAllocations = NewChargeFlatFeeCreditAllocationsClient(tx.config) tx.ChargeFlatFeeInvoicedUsage = NewChargeFlatFeeInvoicedUsageClient(tx.config) tx.ChargeFlatFeePayment = NewChargeFlatFeePaymentClient(tx.config) + tx.ChargeUsageBased = NewChargeUsageBasedClient(tx.config) + tx.ChargeUsageBasedRunCreditAllocations = NewChargeUsageBasedRunCreditAllocationsClient(tx.config) + tx.ChargeUsageBasedRunInvoicedUsage = NewChargeUsageBasedRunInvoicedUsageClient(tx.config) + tx.ChargeUsageBasedRunPayment = NewChargeUsageBasedRunPaymentClient(tx.config) + tx.ChargeUsageBasedRuns = NewChargeUsageBasedRunsClient(tx.config) tx.CurrencyCostBasis = NewCurrencyCostBasisClient(tx.config) tx.CustomCurrency = NewCustomCurrencyClient(tx.config) tx.Customer = NewCustomerClient(tx.config) diff --git a/openmeter/ent/schema/billing.go b/openmeter/ent/schema/billing.go index 3bbad6744f..044873203e 100644 --- a/openmeter/ent/schema/billing.go +++ b/openmeter/ent/schema/billing.go @@ -398,6 +398,10 @@ func (BillingInvoiceLine) Fields() []ent.Field { Optional(). Nillable(), + field.Enum("lifecycle_handler"). + GoType(billing.LifecycleHandler("")). + Default(string(billing.DefaultLifecycleHandler)), + // Deprecated fields field.String("line_ids"). Optional(). diff --git a/openmeter/ent/schema/charges.go b/openmeter/ent/schema/charges.go index 89af79253d..1bddd342d1 100644 --- a/openmeter/ent/schema/charges.go +++ b/openmeter/ent/schema/charges.go @@ -104,6 +104,10 @@ func (Charge) Edges() []ent.Edge { Annotations(entsql.OnDelete(entsql.Cascade)). StorageKey(edge.Column("id")). Unique(), + edge.To("usage_based", ChargeUsageBased.Type). + Annotations(entsql.OnDelete(entsql.Cascade)). + StorageKey(edge.Column("id")). + Unique(), // Billing edge.To("billing_invoice_lines", BillingInvoiceLine.Type), edge.To("billing_split_line_groups", BillingInvoiceSplitLineGroup.Type), diff --git a/openmeter/ent/schema/chargesusagebased.go b/openmeter/ent/schema/chargesusagebased.go new file mode 100644 index 0000000000..f8108e6a4b --- /dev/null +++ b/openmeter/ent/schema/chargesusagebased.go @@ -0,0 +1,236 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/alpacahq/alpacadecimal" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/creditrealization" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/invoicedusage" + "github.com/openmeterio/openmeter/openmeter/billing/charges/models/payment" + "github.com/openmeterio/openmeter/openmeter/billing/charges/usagebased" + "github.com/openmeterio/openmeter/openmeter/productcatalog" + "github.com/openmeterio/openmeter/pkg/framework/entutils" +) + +type ChargeUsageBased struct { + ent.Schema +} + +func (ChargeUsageBased) Mixin() []ent.Mixin { + return []ent.Mixin{ + entutils.NamespaceMixin{}, + entutils.IDMixin{}, + } +} + +func (ChargeUsageBased) Fields() []ent.Field { + return []ent.Field{ + field.Time("invoice_at"). + Immutable(), + + field.Enum("settlement_mode"). + GoType(productcatalog.SettlementMode("")). + Immutable(), + + field.String("discounts"). + GoType(&productcatalog.Discounts{}). + ValueScanner(DiscountsValueScanner). + SchemaType(map[string]string{ + dialect.Postgres: "jsonb", + }). + Optional(). + Nillable(), + + field.String("feature_key"). + NotEmpty(). + Immutable(), + + field.String("price"). + GoType(&productcatalog.Price{}). + ValueScanner(PriceValueScanner). + SchemaType(map[string]string{ + dialect.Postgres: "jsonb", + }). + Immutable(), + } +} + +func (ChargeUsageBased) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("charge", Charge.Type). + Ref("usage_based"). + Unique(). + Required(), + edge.To("runs", ChargeUsageBasedRuns.Type). + Annotations(entsql.OnDelete(entsql.Cascade)), + } +} + +func (ChargeUsageBased) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("namespace", "id"). + Unique(), + } +} + +func (ChargeUsageBased) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "charge_usage_based"}, + } +} + +type ChargeUsageBasedRuns struct { + ent.Schema +} + +func (ChargeUsageBasedRuns) Mixin() []ent.Mixin { + return []ent.Mixin{ + entutils.NamespaceMixin{}, + entutils.IDMixin{}, + entutils.TimeMixin{}, + } +} + +func (ChargeUsageBasedRuns) Fields() []ent.Field { + return []ent.Field{ + field.String("charge_id"). + SchemaType(map[string]string{ + dialect.Postgres: "char(26)", + }). + Immutable(), + + field.Enum("type"). + GoType(usagebased.RealizationRunType("")). + Immutable(), + + field.Time("asof"), + + field.Other("meter_value", alpacadecimal.Decimal{}). + SchemaType(map[string]string{ + dialect.Postgres: "numeric", + }), + } +} + +func (ChargeUsageBasedRuns) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("usage_based", ChargeUsageBased.Type). + Ref("runs"). + Field("charge_id"). + Unique(). + Required(). + Immutable(), + edge.To("credit_allocations", ChargeUsageBasedRunCreditAllocations.Type). + Annotations(entsql.OnDelete(entsql.Cascade)), + edge.To("invoiced_usage", ChargeUsageBasedRunInvoicedUsage.Type). + Unique(). + Annotations(entsql.OnDelete(entsql.Cascade)), + edge.To("payment", ChargeUsageBasedRunPayment.Type). + Unique(). + Annotations(entsql.OnDelete(entsql.Cascade)), + } +} + +func (ChargeUsageBasedRuns) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("namespace", "charge_id"), + } +} + +type ChargeUsageBasedRunCreditAllocations struct { + ent.Schema +} + +func (ChargeUsageBasedRunCreditAllocations) Mixin() []ent.Mixin { + return []ent.Mixin{ + creditrealization.Mixin{}, + } +} + +func (ChargeUsageBasedRunCreditAllocations) Fields() []ent.Field { + return []ent.Field{ + field.String("run_id"). + SchemaType(map[string]string{ + dialect.Postgres: "char(26)", + }). + Immutable(), + } +} + +func (ChargeUsageBasedRunCreditAllocations) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("run", ChargeUsageBasedRuns.Type). + Ref("credit_allocations"). + Field("run_id"). + Unique(). + Required(). + Immutable(), + } +} + +type ChargeUsageBasedRunInvoicedUsage struct { + ent.Schema +} + +func (ChargeUsageBasedRunInvoicedUsage) Mixin() []ent.Mixin { + return []ent.Mixin{ + invoicedusage.Mixin{}, + } +} + +func (ChargeUsageBasedRunInvoicedUsage) Fields() []ent.Field { + return []ent.Field{ + field.String("run_id"). + SchemaType(map[string]string{ + dialect.Postgres: "char(26)", + }). + Immutable(), + } +} + +func (ChargeUsageBasedRunInvoicedUsage) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("run", ChargeUsageBasedRuns.Type). + Ref("invoiced_usage"). + Field("run_id"). + Unique(). + Required(). + Immutable(), + } +} + +type ChargeUsageBasedRunPayment struct { + ent.Schema +} + +func (ChargeUsageBasedRunPayment) Mixin() []ent.Mixin { + return []ent.Mixin{ + payment.InvoicedMixin{}, + } +} + +func (ChargeUsageBasedRunPayment) Fields() []ent.Field { + return []ent.Field{ + field.String("run_id"). + SchemaType(map[string]string{ + dialect.Postgres: "char(26)", + }). + Immutable(), + } +} + +func (ChargeUsageBasedRunPayment) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("run", ChargeUsageBasedRuns.Type). + Ref("payment"). + Field("run_id"). + Unique(). + Required(). + Immutable(), + } +} diff --git a/tools/migrate/migrations/20260316153605_charge_usage_based.down.sql b/tools/migrate/migrations/20260316153605_charge_usage_based.down.sql new file mode 100644 index 0000000000..e7b8116da7 --- /dev/null +++ b/tools/migrate/migrations/20260316153605_charge_usage_based.down.sql @@ -0,0 +1,44 @@ +-- reverse: create index "chargeusagebasedrunpayment_namespace" to table: "charge_usage_based_run_payments" +DROP INDEX "chargeusagebasedrunpayment_namespace"; +-- reverse: create index "chargeusagebasedrunpayment_id" to table: "charge_usage_based_run_payments" +DROP INDEX "chargeusagebasedrunpayment_id"; +-- reverse: create index "chargeusagebasedrunpayment_annotations" to table: "charge_usage_based_run_payments" +DROP INDEX "chargeusagebasedrunpayment_annotations"; +-- reverse: create index "charge_usage_based_run_payments_run_id_key" to table: "charge_usage_based_run_payments" +DROP INDEX "charge_usage_based_run_payments_run_id_key"; +-- reverse: create "charge_usage_based_run_payments" table +DROP TABLE "charge_usage_based_run_payments"; +-- reverse: create index "chargeusagebasedruninvoicedusage_namespace" to table: "charge_usage_based_run_invoiced_usages" +DROP INDEX "chargeusagebasedruninvoicedusage_namespace"; +-- reverse: create index "chargeusagebasedruninvoicedusage_id" to table: "charge_usage_based_run_invoiced_usages" +DROP INDEX "chargeusagebasedruninvoicedusage_id"; +-- reverse: create index "chargeusagebasedruninvoicedusage_annotations" to table: "charge_usage_based_run_invoiced_usages" +DROP INDEX "chargeusagebasedruninvoicedusage_annotations"; +-- reverse: create index "charge_usage_based_run_invoiced_usages_run_id_key" to table: "charge_usage_based_run_invoiced_usages" +DROP INDEX "charge_usage_based_run_invoiced_usages_run_id_key"; +-- reverse: create "charge_usage_based_run_invoiced_usages" table +DROP TABLE "charge_usage_based_run_invoiced_usages"; +-- reverse: create index "chargeusagebasedruncreditallocations_namespace" to table: "charge_usage_based_run_credit_allocations" +DROP INDEX "chargeusagebasedruncreditallocations_namespace"; +-- reverse: create index "chargeusagebasedruncreditallocations_id" to table: "charge_usage_based_run_credit_allocations" +DROP INDEX "chargeusagebasedruncreditallocations_id"; +-- reverse: create index "chargeusagebasedruncreditallocations_annotations" to table: "charge_usage_based_run_credit_allocations" +DROP INDEX "chargeusagebasedruncreditallocations_annotations"; +-- reverse: create "charge_usage_based_run_credit_allocations" table +DROP TABLE "charge_usage_based_run_credit_allocations"; +-- reverse: create index "chargeusagebasedruns_namespace_charge_id" to table: "charge_usage_based_runs" +DROP INDEX "chargeusagebasedruns_namespace_charge_id"; +-- reverse: create index "chargeusagebasedruns_namespace" to table: "charge_usage_based_runs" +DROP INDEX "chargeusagebasedruns_namespace"; +-- reverse: create index "chargeusagebasedruns_id" to table: "charge_usage_based_runs" +DROP INDEX "chargeusagebasedruns_id"; +-- reverse: create "charge_usage_based_runs" table +DROP TABLE "charge_usage_based_runs"; +-- reverse: create index "chargeusagebased_namespace_id" to table: "charge_usage_based" +DROP INDEX "chargeusagebased_namespace_id"; +-- reverse: create index "chargeusagebased_namespace" to table: "charge_usage_based" +DROP INDEX "chargeusagebased_namespace"; +-- reverse: create index "chargeusagebased_id" to table: "charge_usage_based" +DROP INDEX "chargeusagebased_id"; +-- reverse: create "charge_usage_based" table +DROP TABLE "charge_usage_based"; diff --git a/tools/migrate/migrations/20260316153605_charge_usage_based.up.sql b/tools/migrate/migrations/20260316153605_charge_usage_based.up.sql new file mode 100644 index 0000000000..501d733811 --- /dev/null +++ b/tools/migrate/migrations/20260316153605_charge_usage_based.up.sql @@ -0,0 +1,123 @@ +-- create "charge_usage_based" table +CREATE TABLE "charge_usage_based" ( + "id" character(26) NOT NULL, + "namespace" character varying NOT NULL, + "invoice_at" timestamptz NOT NULL, + "settlement_mode" character varying NOT NULL, + "discounts" jsonb NULL, + "feature_key" character varying NOT NULL, + "price" jsonb NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "charge_usage_based_charges_usage_based" FOREIGN KEY ("id") REFERENCES "charges" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- create index "chargeusagebased_id" to table: "charge_usage_based" +CREATE UNIQUE INDEX "chargeusagebased_id" ON "charge_usage_based" ("id"); +-- create index "chargeusagebased_namespace" to table: "charge_usage_based" +CREATE INDEX "chargeusagebased_namespace" ON "charge_usage_based" ("namespace"); +-- create index "chargeusagebased_namespace_id" to table: "charge_usage_based" +CREATE UNIQUE INDEX "chargeusagebased_namespace_id" ON "charge_usage_based" ("namespace", "id"); +-- create "charge_usage_based_runs" table +CREATE TABLE "charge_usage_based_runs" ( + "id" character(26) NOT NULL, + "namespace" character varying NOT NULL, + "created_at" timestamptz NOT NULL, + "updated_at" timestamptz NOT NULL, + "deleted_at" timestamptz NULL, + "type" character varying NOT NULL, + "asof" timestamptz NOT NULL, + "meter_value" numeric NOT NULL, + "charge_id" character(26) NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "charge_usage_based_runs_charge_usage_based_runs" FOREIGN KEY ("charge_id") REFERENCES "charge_usage_based" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- create index "chargeusagebasedruns_id" to table: "charge_usage_based_runs" +CREATE UNIQUE INDEX "chargeusagebasedruns_id" ON "charge_usage_based_runs" ("id"); +-- create index "chargeusagebasedruns_namespace" to table: "charge_usage_based_runs" +CREATE INDEX "chargeusagebasedruns_namespace" ON "charge_usage_based_runs" ("namespace"); +-- create index "chargeusagebasedruns_namespace_charge_id" to table: "charge_usage_based_runs" +CREATE INDEX "chargeusagebasedruns_namespace_charge_id" ON "charge_usage_based_runs" ("namespace", "charge_id"); +-- create "charge_usage_based_run_credit_allocations" table +CREATE TABLE "charge_usage_based_run_credit_allocations" ( + "id" character(26) NOT NULL, + "line_id" character(26) NULL, + "amount" numeric NOT NULL, + "service_period_from" timestamptz NOT NULL, + "service_period_to" timestamptz NOT NULL, + "ledger_transaction_group_id" character(26) NOT NULL, + "namespace" character varying NOT NULL, + "created_at" timestamptz NOT NULL, + "updated_at" timestamptz NOT NULL, + "deleted_at" timestamptz NULL, + "annotations" jsonb NULL, + "run_id" character(26) NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "charge_usage_based_run_credit_allocations_charge_usage_based_ru" FOREIGN KEY ("run_id") REFERENCES "charge_usage_based_runs" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- create index "chargeusagebasedruncreditallocations_annotations" to table: "charge_usage_based_run_credit_allocations" +CREATE INDEX "chargeusagebasedruncreditallocations_annotations" ON "charge_usage_based_run_credit_allocations" USING gin ("annotations"); +-- create index "chargeusagebasedruncreditallocations_id" to table: "charge_usage_based_run_credit_allocations" +CREATE UNIQUE INDEX "chargeusagebasedruncreditallocations_id" ON "charge_usage_based_run_credit_allocations" ("id"); +-- create index "chargeusagebasedruncreditallocations_namespace" to table: "charge_usage_based_run_credit_allocations" +CREATE INDEX "chargeusagebasedruncreditallocations_namespace" ON "charge_usage_based_run_credit_allocations" ("namespace"); +-- create "charge_usage_based_run_invoiced_usages" table +CREATE TABLE "charge_usage_based_run_invoiced_usages" ( + "id" character(26) NOT NULL, + "line_id" character(26) NULL, + "service_period_from" timestamptz NOT NULL, + "service_period_to" timestamptz NOT NULL, + "mutable" boolean NOT NULL, + "ledger_transaction_group_id" character(26) NULL, + "namespace" character varying NOT NULL, + "created_at" timestamptz NOT NULL, + "updated_at" timestamptz NOT NULL, + "deleted_at" timestamptz NULL, + "annotations" jsonb NULL, + "amount" numeric NOT NULL, + "taxes_total" numeric NOT NULL, + "taxes_inclusive_total" numeric NOT NULL, + "taxes_exclusive_total" numeric NOT NULL, + "charges_total" numeric NOT NULL, + "discounts_total" numeric NOT NULL, + "credits_total" numeric NOT NULL, + "total" numeric NOT NULL, + "run_id" character(26) NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "charge_usage_based_run_invoiced_usages_charge_usage_based_runs_" FOREIGN KEY ("run_id") REFERENCES "charge_usage_based_runs" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- create index "charge_usage_based_run_invoiced_usages_run_id_key" to table: "charge_usage_based_run_invoiced_usages" +CREATE UNIQUE INDEX "charge_usage_based_run_invoiced_usages_run_id_key" ON "charge_usage_based_run_invoiced_usages" ("run_id"); +-- create index "chargeusagebasedruninvoicedusage_annotations" to table: "charge_usage_based_run_invoiced_usages" +CREATE INDEX "chargeusagebasedruninvoicedusage_annotations" ON "charge_usage_based_run_invoiced_usages" USING gin ("annotations"); +-- create index "chargeusagebasedruninvoicedusage_id" to table: "charge_usage_based_run_invoiced_usages" +CREATE UNIQUE INDEX "chargeusagebasedruninvoicedusage_id" ON "charge_usage_based_run_invoiced_usages" ("id"); +-- create index "chargeusagebasedruninvoicedusage_namespace" to table: "charge_usage_based_run_invoiced_usages" +CREATE INDEX "chargeusagebasedruninvoicedusage_namespace" ON "charge_usage_based_run_invoiced_usages" ("namespace"); +-- create "charge_usage_based_run_payments" table +CREATE TABLE "charge_usage_based_run_payments" ( + "id" character(26) NOT NULL, + "line_id" character(26) NOT NULL, + "service_period_from" timestamptz NOT NULL, + "service_period_to" timestamptz NOT NULL, + "status" character varying NOT NULL, + "amount" numeric NOT NULL, + "authorized_transaction_group_id" character(26) NULL, + "authorized_at" timestamptz NULL, + "settled_transaction_group_id" character(26) NULL, + "settled_at" timestamptz NULL, + "namespace" character varying NOT NULL, + "created_at" timestamptz NOT NULL, + "updated_at" timestamptz NOT NULL, + "deleted_at" timestamptz NULL, + "annotations" jsonb NULL, + "run_id" character(26) NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "charge_usage_based_run_payments_charge_usage_based_runs_payment" FOREIGN KEY ("run_id") REFERENCES "charge_usage_based_runs" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- create index "charge_usage_based_run_payments_run_id_key" to table: "charge_usage_based_run_payments" +CREATE UNIQUE INDEX "charge_usage_based_run_payments_run_id_key" ON "charge_usage_based_run_payments" ("run_id"); +-- create index "chargeusagebasedrunpayment_annotations" to table: "charge_usage_based_run_payments" +CREATE INDEX "chargeusagebasedrunpayment_annotations" ON "charge_usage_based_run_payments" USING gin ("annotations"); +-- create index "chargeusagebasedrunpayment_id" to table: "charge_usage_based_run_payments" +CREATE UNIQUE INDEX "chargeusagebasedrunpayment_id" ON "charge_usage_based_run_payments" ("id"); +-- create index "chargeusagebasedrunpayment_namespace" to table: "charge_usage_based_run_payments" +CREATE INDEX "chargeusagebasedrunpayment_namespace" ON "charge_usage_based_run_payments" ("namespace"); diff --git a/tools/migrate/migrations/20260317101158_billing-charge-handlers.down.sql b/tools/migrate/migrations/20260317101158_billing-charge-handlers.down.sql new file mode 100644 index 0000000000..5f59ce7bbb --- /dev/null +++ b/tools/migrate/migrations/20260317101158_billing-charge-handlers.down.sql @@ -0,0 +1,2 @@ +-- reverse: modify "billing_invoice_lines" table +ALTER TABLE "billing_invoice_lines" DROP COLUMN "lifecycle_handler"; diff --git a/tools/migrate/migrations/20260317101158_billing-charge-handlers.up.sql b/tools/migrate/migrations/20260317101158_billing-charge-handlers.up.sql new file mode 100644 index 0000000000..402e831e77 --- /dev/null +++ b/tools/migrate/migrations/20260317101158_billing-charge-handlers.up.sql @@ -0,0 +1,2 @@ +-- modify "billing_invoice_lines" table +ALTER TABLE "billing_invoice_lines" ADD COLUMN "lifecycle_handler" character varying NOT NULL DEFAULT 'default'; diff --git a/tools/migrate/migrations/atlas.sum b/tools/migrate/migrations/atlas.sum index c4eb0c27cc..0d78c12067 100644 --- a/tools/migrate/migrations/atlas.sum +++ b/tools/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:M6XvMbZCczT9yA1sefMLUDf36xEo+tCMPr3xOe36h7E= +h1:ZisWVKIspnAPA+wtNtHwSLdPYKKg/QpWHU/uZ+LKIiI= 20240826120919_init.up.sql h1:tc1V91/smlmaeJGQ8h+MzTEeFjjnrrFDbDAjOYJK91o= 20240903155435_entitlement-expired-index.up.sql h1:Hp8u5uckmLXc1cRvWU0AtVnnK8ShlpzZNp8pbiJLhac= 20240917172257_billing-entities.up.sql h1:Q1dAMo0Vjiit76OybClNfYPGC5nmvov2/M2W1ioi4Kw= @@ -156,3 +156,5 @@ h1:M6XvMbZCczT9yA1sefMLUDf36xEo+tCMPr3xOe36h7E= 20260305140658_billing-charges-credit-purchase.up.sql h1:nMArFrsYCVfgPrG5jvEaD+98w0dVW6Vo9FNWnl90rVU= 20260305173559_feature_cost_add.up.sql h1:8RoPNNmQsOSNKvOwjP9hdYZeRJxbrmTSy1I6MhB135A= 20260314200257_charge-normalize-db.up.sql h1:QEOgzspwOq0za+tiIsr+m6jxipJtqp1WxPz4wAcb8ik= +20260316153605_charge_usage_based.up.sql h1:pnBXhfL3uXKM0Ocnxe6g7VdrfpKQyHMAOn5eHnSpa5M= +20260317101158_billing-charge-handlers.up.sql h1:CF8QFZMCWhNTENfsVq5czEt1e2t2QQasW8BsjwImRZA=